#!/usr/bin/env node "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // var define_KSQL_DOCS_default; var init_define_KSQL_DOCS = __esm({ ""() { define_KSQL_DOCS_default = { languageReference: { title: "kSQL \u8A00\u8A9E\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9", index: "# kSQL \u8A00\u8A9E\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9 index\n\nSyntax and dialect reference for kSQL. Read only the section needed for the current task.\n\nSource: `docs/ksql_language_reference.md`\n\n## Sections\n\n- [1. \u57FA\u672C\u30EB\u30FC\u30EB](ksql://language-reference/01-basic-rules)\n- [2. SELECT](ksql://language-reference/02-select)\n- [3. \u7B97\u8853\u5F0F](ksql://language-reference/03-arithmetic-expressions)\n- [4. CASE WHEN](ksql://language-reference/04-case-when)\n- [5. \u6587\u5B57\u5217\u30FB\u6570\u5024\u95A2\u6570](ksql://language-reference/05-string-number-functions)\n- [6. WHERE \u53E5](ksql://language-reference/06-where)\n- [7. JOIN](ksql://language-reference/07-join)\n- [8. GROUP BY / \u96C6\u8A08\u95A2\u6570](ksql://language-reference/08-group-by-aggregates)\n- [9. HAVING](ksql://language-reference/09-having)\n- [10. ORDER BY](ksql://language-reference/10-order-by)\n- [11. LIMIT / OFFSET](ksql://language-reference/11-limit-offset)\n- [12. UNION / UNION ALL](ksql://language-reference/12-union)\n- [13. WITH \u53E5\uFF08CTE\uFF09](ksql://language-reference/13-with-cte)\n- [14. SHOW APPS / DESCRIBE](ksql://language-reference/14-show-apps-describe)\n- [15. INSERT](ksql://language-reference/15-insert)\n- [16. UPDATE](ksql://language-reference/16-update)\n- [17. UPSERT](ksql://language-reference/17-upsert)\n- [18. DELETE](ksql://language-reference/18-delete)\n- [19. \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB](ksql://language-reference/19-subtable-virtual-table)\n- [20. REORDER](ksql://language-reference/20-reorder)\n- [21. \u30B5\u30D6\u30AF\u30A8\u30EA](ksql://language-reference/21-subqueries)\n- [22. \u5236\u9650\u4E8B\u9805](ksql://language-reference/22-limitations)\n- [23. UI \u6A5F\u80FD](ksql://language-reference/23-ui-features)\n- [24. EXPLAIN](ksql://language-reference/24-explain)\n- [25. \u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB](ksql://language-reference/25-batch-temp-tables)\n- [26. ASSERT](ksql://language-reference/26-assert)\n\nIndex URI: ksql://language-reference", sections: { "01-basic-rules": { heading: "1. \u57FA\u672C\u30EB\u30FC\u30EB", text: '## 1. \u57FA\u672C\u30EB\u30FC\u30EB\r\n\r\n### \u30C6\u30FC\u30D6\u30EB\u540D\r\n\r\nkintone \u306E\u30A2\u30D7\u30EA ID \u3092 `APP` + \u6570\u5B57\u3067\u6307\u5B9A\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nAPP100 -- \u30A2\u30D7\u30EA ID 100\r\nAPP42 -- \u30A2\u30D7\u30EA ID 42\r\nAPP100$\u660E\u7D30 -- \u30A2\u30D7\u30EA ID 100 \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u300C\u660E\u7D30\u300D\r\n```\r\n\r\n\u5927\u6587\u5B57\u30FB\u5C0F\u6587\u5B57\u306F\u533A\u5225\u3057\u307E\u305B\u3093\uFF08`app100` \u3082\u6709\u52B9\uFF09\u3002\r\n\r\n### CLI \u62E1\u5F35: `APP@profile`\r\n\r\nCLI \u3067\u306F\u30C6\u30FC\u30D6\u30EB\u53C2\u7167\u306E\u672B\u5C3E\u306B `@profile` \u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nAPP100@dev -- APP100 \u3092 dev \u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u3067\u5B9F\u884C\r\nAPP80$\u660E\u7D30@guest -- \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u53C2\u7167\u3067\u3082\u6307\u5B9A\u53EF\u80FD\r\n```\r\n\r\n\u30EB\u30FC\u30EB:\r\n\r\n- `@profile` \u306A\u3057\u306E `APPxxx` \u306F\u65E2\u5B9A profile\uFF08`--profile` / config\uFF09\u3092\u4F7F\u7528\r\n- profile \u540D\u306E\u5927\u6587\u5B57\u30FB\u5C0F\u6587\u5B57\u306F\u533A\u5225\u3057\u307E\u305B\u3093\uFF08`APP100@Dev` \u3082\u6709\u52B9\uFF09\r\n- \u540C\u4E00 SQL \u5185\u3067\u540C\u4E00 APP \u306B\u7570\u306A\u308B profile \u3092\u6DF7\u5728\u53EF\u80FD\uFF08\u5225\u74B0\u5883\u306E\u5225\u30A2\u30D7\u30EA\u3068\u3057\u3066\u6271\u3046\uFF09\r\n- \u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u30FB\u30B3\u30E1\u30F3\u30C8\u4E2D\u306E `APP100@dev` \u306F `@profile` \u69CB\u6587\u3068\u3057\u3066\u89E3\u91C8\u3057\u307E\u305B\u3093\r\n- \u30D7\u30E9\u30B0\u30A4\u30F3\u5074\u3067\u306F `@profile` \u975E\u5BFE\u5FDC\u3067\u3059\uFF08`APP100@dev` \u3092\u542B\u3080 SQL \u306F\u30A8\u30E9\u30FC\uFF09\r\n\r\n### CLI / MCP \u62E1\u5F35: \u8AD6\u7406\u30A2\u30D7\u30EA\u53C2\u7167 `LAPP_`\r\n\r\n\u540C\u3058\u7528\u9014\u30FB\u540C\u3058\u30D5\u30A3\u30FC\u30EB\u30C9\u69CB\u6210\u306E\u30A2\u30D7\u30EA\u3067\u7269\u7406 ID \u3060\u3051\u304C\u74B0\u5883\u3054\u3068\u306B\u7570\u306A\u308B\u5834\u5408\u3001\u8AD6\u7406\u540D\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT * FROM LAPP_ORDERS\r\nSELECT * FROM LAPP_ORDERS@prod\r\nSELECT * FROM LAPP_ORDERS$\u660E\u7D30@prod\r\n```\r\n\r\n`LAPP_ORDERS` \u306F\u5B9F\u52B9 profile \u306E `logicalApps.ORDERS` \u306B\u8A2D\u5B9A\u3055\u308C\u305F\u7269\u7406\u30A2\u30D7\u30EA ID\u3078\u3001\u5B9F\u884C\u524D\u306B\u89E3\u6C7A\u3055\u308C\u307E\u3059\u3002`APP100` \u306F\u5F93\u6765\u3069\u304A\u308A\u5E38\u306B\u7269\u7406 ID 100 \u3067\u3042\u308A\u3001\u6697\u9ED9\u306B\u8AD6\u7406\u89E3\u6C7A\u3055\u308C\u307E\u305B\u3093\u3002\r\n\r\n```json\r\n{\r\n "profiles": {\r\n "dev": { "logicalApps": { "ORDERS": 100 } },\r\n "prod": { "logicalApps": { "ORDERS": 1200 } }\r\n }\r\n}\r\n```\r\n\r\n\u69CB\u6587\u3068\u5236\u7D04:\r\n\r\n- `LAPP_` \u3068\u8AD6\u7406\u540D\u306F ASCII \u306E\u7BC4\u56F2\u3067\u5927\u5C0F\u6587\u5B57\u3092\u533A\u5225\u3057\u306A\u3044\r\n- \u8AD6\u7406\u540D\u306F `[A-Za-z][A-Za-z0-9_]{0,63}`\r\n- config \u306E\u30AD\u30FC\u306F\u88F8\u306E\u8AD6\u7406\u540D\uFF08`ORDERS`\uFF09\u3002`APP100`\u3001`100`\u3001`LAPP_ORDERS` \u306F\u7981\u6B62\r\n- \u672A\u5B9A\u7FA9\u8AD6\u7406\u540D\u3001\u672A\u77E5 profile\u3001`allowPhysicalAppRefs: false` \u306E profile \u306B\u5BFE\u3059\u308B\u7269\u7406\u53C2\u7167\u306F API \u547C\u3073\u51FA\u3057\u524D\u306B\u30A8\u30E9\u30FC\r\n- validation \u306F `source`\u3001`logicalName`\u3001\u5185\u90E8 `mappedAppId`\u3001\u6700\u7D42 `appId`\u3001`profile` \u3092\u8FD4\u3059\r\n- EXPLAIN \u3068\u5229\u7528\u8005\u5411\u3051\u8A3A\u65AD\u306F\u8AD6\u7406\u540D\u30FB\u6700\u7D42\u7269\u7406 ID\u30FBprofile \u3092\u8868\u793A\u3057\u3001\u5185\u90E8 mapped ID \u306F\u8868\u793A\u3057\u306A\u3044\r\n- CLI \u306E `DELETE FROM LAPP_ORDERS@prod ...` \u306F\u660E\u793A profile \u5236\u7D04\u306B\u3088\u308A\u62D2\u5426\u3002MCP\u3067\u306F\u8A31\u53EF\r\n- Node.js runtime\uFF08CLI / MCP\uFF09\u306E\u6A5F\u80FD\u3067\u3042\u308A\u3001\u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306F\u975E\u5BFE\u5FDC\r\n\r\n### \u30D5\u30A3\u30FC\u30EB\u30C9\u540D\uFF08\u8B58\u5225\u5B50\uFF09\r\n\r\n- \u65E5\u672C\u8A9E\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u3092\u30AF\u30A9\u30FC\u30C8\u306A\u3057\u3067\u4F7F\u7528\u3067\u304D\u307E\u3059\r\n- \u30B9\u30DA\u30FC\u30B9\u30FB\u7279\u6B8A\u6587\u5B57\u3092\u542B\u3080\u540D\u524D\u306F\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\r\n- \u30AD\u30FC\u30EF\u30FC\u30C9\uFF08`SELECT`\u3001`FROM` \u7B49\uFF09\u3068\u540C\u540D\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3082\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\r\n\r\n```sql\r\nSELECT \u91D1\u984D, \u62C5\u5F53\u8005\u540D FROM APP100\r\nSELECT `\u53D7\u6CE8 \u91D1\u984D`, `order` FROM APP100\r\n```\r\n\r\n### \u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\r\n\r\n\u30B7\u30F3\u30B0\u30EB\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\u3002 \r\n\u6587\u5B57\u5217\u4E2D\u306E\u30B7\u30F3\u30B0\u30EB\u30AF\u30A9\u30FC\u30C8\u306F `\'\'`\uFF082\u3064\u9023\u7D9A\uFF09\u3067\u30A8\u30B9\u30B1\u30FC\u30D7\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = \'\u5B8C\u4E86\'\r\nWHERE \u5099\u8003 = \'it\'\'s done\' -- it\'s done\r\n```\r\n\r\n### \u6570\u5024\u30EA\u30C6\u30E9\u30EB\r\n\r\n\u6574\u6570\u30FB\u5C0F\u6570\u3092\u305D\u306E\u307E\u307E\u8A18\u8FF0\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nWHERE \u91D1\u984D > 10000\r\nWHERE \u9032\u6357\u7387 >= 0.5\r\n```\r\n\r\n### \u5927\u6587\u5B57\u30FB\u5C0F\u6587\u5B57\r\n\r\n\u30AD\u30FC\u30EF\u30FC\u30C9\uFF08`SELECT`\u3001`WHERE` \u7B49\uFF09\u306F\u5927\u6587\u5B57\u30FB\u5C0F\u6587\u5B57\u3092\u533A\u5225\u3057\u307E\u305B\u3093\u3002 \r\n\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u306F kintone \u306E\u5B9A\u7FA9\u306B\u5F93\u3044\u307E\u3059\uFF08\u901A\u5E38\u306F\u533A\u5225\u3042\u308A\uFF09\u3002\r\n\r\n### \u30BB\u30DF\u30B3\u30ED\u30F3\r\n\r\n\u6587\u672B\u306E\u30BB\u30DF\u30B3\u30ED\u30F3\uFF08`;`\uFF09\u306F\u4EFB\u610F\u3067\u3059\u3002\r\n\r\n---', uri: "ksql://language-reference/01-basic-rules" }, "02-select": { heading: "2. SELECT", text: "## 2. SELECT\r\n\r\n### \u57FA\u672C\u69CB\u6587\r\n\r\n```sql\r\nSELECT [DISTINCT] \u30AB\u30E9\u30E0\u30EA\u30B9\u30C8\r\n[FROM \u30C6\u30FC\u30D6\u30EB\u540D [AS \u30A8\u30A4\u30EA\u30A2\u30B9]]\r\n[JOIN\u53E5]\r\n[WHERE \u6761\u4EF6]\r\n[GROUP BY \u30D5\u30A3\u30FC\u30EB\u30C9\u30EA\u30B9\u30C8]\r\n[HAVING \u6761\u4EF6]\r\n[ORDER BY \u30AD\u30FC\u30EA\u30B9\u30C8]\r\n[LIMIT \u4EF6\u6570 [OFFSET \u30B9\u30AD\u30C3\u30D7\u6570]]\r\n```\r\n\r\n`FROM` \u306F\u7701\u7565\u53EF\u80FD\u3067\u3059\uFF08\u5F0F\u5C02\u7528 SELECT\uFF09\u3002\r\n\r\n```sql\r\nSELECT 'xxx' AS a\r\nSELECT 'ABC' as a;\r\n```\r\n\r\n\u5236\u7D04:\r\n\r\n- `FROM` \u7701\u7565\u6642\u306F\u5F0F\u5217\u306E\u307F\u5BFE\u5FDC\uFF08\u4F8B: \u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u3001\u6570\u5024\u6F14\u7B97\u3001\u95A2\u6570\uFF09\r\n- `SELECT *` / \u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\uFF08\u4F8B: `SELECT \u9867\u5BA2\u540D`\uFF09\u306F\u975E\u5BFE\u5FDC\r\n\r\n### \u5168\u30D5\u30A3\u30FC\u30EB\u30C9\u53D6\u5F97\r\n\r\n```sql\r\nSELECT * FROM APP100\r\n```\r\n\r\n### \u7279\u5B9A\u30D5\u30A3\u30FC\u30EB\u30C9\u6307\u5B9A\r\n\r\n```sql\r\nSELECT \u6C0F\u540D, \u91D1\u984D, \u30B9\u30C6\u30FC\u30BF\u30B9 FROM APP100\r\n```\r\n\r\n### \u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u5217\r\n\r\n```sql\r\nSELECT \u9867\u5BA2\u540D, 'XXX' AS a FROM APP60\r\n```\r\n\r\n\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u5217\u306F `AS` \u3067\u30A8\u30A4\u30EA\u30A2\u30B9\u3092\u4ED8\u3051\u3066\u5229\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT 'XXX' AS a\r\n```\r\n\r\n### AS \u30A8\u30A4\u30EA\u30A2\u30B9\r\n\r\n```sql\r\nSELECT \u6C0F\u540D AS name, \u91D1\u984D AS amount FROM APP100\r\n```\r\n\r\n### DISTINCT\uFF08\u91CD\u8907\u9664\u53BB\uFF09\r\n\r\n```sql\r\nSELECT DISTINCT \u90FD\u9053\u5E9C\u770C FROM APP100\r\nSELECT DISTINCT \u30B9\u30C6\u30FC\u30BF\u30B9, \u62C5\u5F53\u8005 FROM APP100\r\n```\r\n\r\n### JOIN \u3067\u306E\u4FEE\u98FE\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\r\n\r\nJOIN \u3092\u4F7F\u3046\u5834\u5408\u3001`\u30A8\u30A4\u30EA\u30A2\u30B9.\u30D5\u30A3\u30FC\u30EB\u30C9\u540D` \u306E\u5F62\u5F0F\u3067\u6307\u5B9A\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT a.\u6C0F\u540D, b.\u91D1\u984D\r\nFROM APP100 AS a\r\nINNER JOIN APP200 AS b ON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n```\r\n\r\n`FROM/JOIN` \u306E\u30C6\u30FC\u30D6\u30EB alias \u306F `AS` \u7701\u7565\u5F62\u3082\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT a.\u6C0F\u540D, b.\u91D1\u984D\r\nFROM APP100 a\r\nINNER JOIN APP200 b ON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n```\r\n\r\n---", uri: "ksql://language-reference/02-select" }, "03-arithmetic-expressions": { heading: "3. \u7B97\u8853\u5F0F", text: "## 3. \u7B97\u8853\u5F0F\r\n\r\nSELECT \u5217\u30FBWHERE \u53E5\u30FBORDER BY\u30FBUPDATE SET \u3067\u56DB\u5247\u6F14\u7B97\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n| \u6F14\u7B97\u5B50 | \u610F\u5473 |\r\n|--------|------|\r\n| `+` | \u52A0\u7B97 |\r\n| `-` | \u6E1B\u7B97 |\r\n| `*` | \u4E57\u7B97 |\r\n| `/` | \u9664\u7B97\uFF08\u30BC\u30ED\u9664\u7B97\u306F NaN\uFF09 |\r\n| `%` | \u5270\u4F59\u30FB\u4F59\u308A\uFF08\u30BC\u30ED\u9664\u7B97\u306F NaN\uFF09 |\r\n\r\n```sql\r\n-- SELECT \u5217\u3067\u7B97\u8853\u5F0F\r\nSELECT \u5358\u4FA1 * \u6570\u91CF AS \u5C0F\u8A08 FROM APP100\r\nSELECT \u91D1\u984D * 1.1 AS \u7A0E\u8FBC\u91D1\u984D FROM APP100\r\nSELECT (\u58F2\u4E0A - \u539F\u4FA1) / \u58F2\u4E0A AS \u7C97\u5229\u7387 FROM APP100\r\nSELECT \u6570\u91CF % 3 AS \u4F59\u308A FROM APP100\r\n\r\n-- \u95A2\u6570\u306E\u7D50\u679C\u3082\u88AB\u6F14\u7B97\u5B50\u3068\u3057\u3066\u4F7F\u7528\u53EF\u80FD\r\nSELECT ROUND(\u5408\u8A08\u8CBB\u7528) / 2 AS \u534A\u984D FROM APP100\r\nSELECT LENGTH(\u9867\u5BA2\u540D) * 100 AS \u30B9\u30B3\u30A2 FROM APP100\r\n\r\n-- WHERE \u53E5\u306E\u5DE6\u8FBA\u30FB\u53F3\u8FBA\u306B\u7B97\u8853\u5F0F\uFF08FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\uFF09\r\nWHERE \u91D1\u984D * 1.1 > 10000\r\nWHERE (\u5358\u4FA1 + \u9001\u6599) * \u6570\u91CF < 5000\r\nWHERE \u7A0E\u8FBC\u91D1\u984D = \u91D1\u984D * 1.1\r\n```\r\n\r\n\u6F14\u7B97\u5B50\u306E\u512A\u5148\u9806\u4F4D\u306F\u901A\u5E38\u306E\u7B97\u8853\u898F\u5247\uFF08`*` `/` > `+` `-`\uFF09\u306B\u5F93\u3044\u3001\u30AB\u30C3\u30B3\u3067\u660E\u793A\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\r\n\r\n> **WHERE \u7B97\u8853\u5F0F\u306F FULL_SCAN \u30E2\u30FC\u30C9:** kintone API \u306B\u5909\u63DB\u3067\u304D\u306A\u3044\u305F\u3081\u5168\u4EF6\u53D6\u5F97\u5F8C JS \u3067\u8A55\u4FA1\u3057\u307E\u3059\u3002\r\n\r\n### \u7B97\u8853\u306E\u7CBE\u5EA6\u3068\u7A7A\u30BB\u30EB\uFF08\u91CD\u8981\u306A\u5236\u7D04\uFF09\r\n\r\n\u7B97\u8853\u5F0F\u306F **IEEE 754 \u500D\u7CBE\u5EA6\u6D6E\u52D5\u5C0F\u6570\u70B9\uFF08JavaScript \u306E number\uFF09** \u3067\u8A55\u4FA1\u3057\u3001\u7D50\u679C\u306E\u4E38\u3081\u30FB\u91CF\u5B50\u5316\u306F\u884C\u3044\u307E\u305B\u3093\u3002`SUM` / `AVG` \u3068\u7D71\u8A08\u96C6\u7D04\uFF08\u5206\u6563\u30FB\u6A19\u6E96\u504F\u5DEE\u30FB\u4E2D\u592E\u5024\uFF09\u3082 binary64 \u3067\u8A08\u7B97\u3057\u307E\u3059\u3002\u7D71\u8A08\u96C6\u7D04\u306F\u53B3\u5BC6 10 \u9032\u6F14\u7B97\u306E\u5BFE\u8C61\u5916\u3067\u3059\u3002\u6B21\u306E\u5236\u7D04\u304C\u3042\u308A\u307E\u3059\u3002\r\n\r\n**1. \u5C0F\u6570\u306E\u8868\u73FE\u8AA4\u5DEE**\uFF08\u6841\u6570\u306B\u3088\u3089\u305A\u3001\u5024\u306B\u4F9D\u5B58\u3057\u3066\u767A\u751F\u3057\u307E\u3059\uFF09\r\n\r\n```sql\r\nSELECT \u91D1\u984D * 1.1 FROM APP100 -- \u91D1\u984D=3000 \u2192 3300.0000000000005\r\n -- \u91D1\u984D=1000 \u2192 1100\uFF08\u3053\u306E\u5024\u3067\u306F\u305F\u307E\u305F\u307E\u8AA4\u5DEE\u306A\u3057\uFF09\r\nSELECT 0.1 + 0.2 -- 0.30000000000000004\r\n```\r\n\r\n\u3053\u306E\u305F\u3081 `WHERE \u91D1\u984D * 1.1 = 3300` \u306E\u3088\u3046\u306A**\u7B97\u8853\u7D50\u679C\u306E\u7B49\u5024\u6BD4\u8F03\u306F\u5931\u6557\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059**\u3002\u7B49\u5024\u3067\u6BD4\u8F03\u3059\u308B\u5834\u5408\u306F `ROUND(\u91D1\u984D * 1.1, 2)` \u306E\u3088\u3046\u306B\u4E38\u3081\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n**2. \u7B97\u8853\u306E\u6709\u52B9\u6841\u306F 15\u301C17 \u6841**\uFF08\u6574\u6570\u306F 9,007,199,254,740,992 = 2^53 \u307E\u3067\u6B63\u78BA\uFF09\r\n\r\n```sql\r\nSELECT 9007199254740993 + 1 -- \u2192 9007199254740992\uFF08+1 \u304C\u7D50\u679C\u306B\u53CD\u6620\u3055\u308C\u306A\u3044\uFF09\r\n```\r\n\r\n\u5358\u7D14\u306A\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u306F\u5143\u306E10\u9032\u5B57\u53E5\u3092\u4FDD\u6301\u3059\u308B\u305F\u3081\u3001\u6BD4\u8F03\u30FBREST query\u30FB\u5358\u7D14DML\u3067\u306F\u4E38\u307E\u308A\u307E\u305B\u3093\u3002`1e3` / `1.2E-3` \u306E\u6307\u6570\u8868\u8A18\u3082\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\u4E00\u65B9\u3001\u7B97\u8853\u3078\u5165\u308B\u3068JavaScript number\u306B\u306A\u308A\u3001\u5B89\u5168\u6574\u6570\u57DF\u3092\u8D85\u3048\u308B\u6574\u6570\u3067\u306F1\u306E\u4F4D\u306E\u5909\u5316\u304C\u6D88\u3048\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002\r\n\r\n**3. kintone \u306E\u8A08\u7B97\u30D5\u30A3\u30FC\u30EB\u30C9\u3068\u306F\u7D50\u679C\u304C\u7570\u306A\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059**\r\n\r\nkintone \u306E\u8A08\u7B97\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u30B5\u30FC\u30D0\u30FC\u5074\u306E 10 \u9032\u6F14\u7B97\uFF0B\u30A2\u30D7\u30EA\u306E `numberPrecision` \u8A2D\u5B9A\uFF08\u6841\u6570\u30FB\u4E38\u3081\u30E2\u30FC\u30C9\uFF09\u3067\u4E38\u3081\u305F\u5024\u3092\u8FD4\u3057\u307E\u3059\u3002\u540C\u3058\u5F0F\u3067\u3082 kSQL \u306E\u7B97\u8853\u306F\u751F\u306E\u6D6E\u52D5\u5C0F\u6570\u70B9\u5024\u3092\u8FD4\u3059\u305F\u3081\u3001\u7D50\u679C\u304C\u4E00\u81F4\u3057\u306A\u3044\u3053\u3068\u304C\u3042\u308A\u307E\u3059\uFF08\u5B9F\u6E2C: \u5B9A\u7FA9\u304C\u540C\u3058 `\u91D1\u984D * 1.1` \u3067\u3001\u8A08\u7B97\u30D5\u30A3\u30FC\u30EB\u30C9= `3300`\u30FBkSQL= `3300.0000000000005`\uFF09\u3002**\u7CBE\u5EA6\u304C\u91CD\u8981\u306A\u8A08\u7B97\u306F kintone \u306E\u8A08\u7B97\u30D5\u30A3\u30FC\u30EB\u30C9\u5074\u306B\u5BC4\u305B\u3001kSQL \u3067\u306F\u305D\u306E\u5024\u3092\u53C2\u7167\u3059\u308B**\u306E\u304C\u5B89\u5168\u3067\u3059\u3002\r\n\r\n**4. \u7A7A\u30BB\u30EB\u306F 0 \u3068\u3057\u3066\u8A08\u7B97\u3055\u308C\u307E\u3059**\r\n\r\n```sql\r\nSELECT \u91D1\u984D + 1 FROM APP100 -- \u91D1\u984D\u304C\u7A7A\u30BB\u30EB \u2192 1\uFF08\u91D1\u984D=0 \u306E\u884C\u3068\u533A\u5225\u3067\u304D\u306A\u3044\uFF09\r\n```\r\n\r\nkintone \u306E\u672A\u8A2D\u5B9A\u5024\u306F\u7A7A\u6587\u5B57\u3067\u3001\u7B97\u8853\u5F0F\u3067\u306F 0 \u306B\u5909\u63DB\u3055\u308C\u307E\u3059\u3002\u7A7A\u30BB\u30EB\u3092\u8A08\u7B97\u5BFE\u8C61\u304B\u3089\u9664\u304D\u305F\u3044\u5834\u5408\u306F `WHERE \u91D1\u984D != ''` \u3067\u9664\u5916\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u6BD4\u8F03\u30FBORDER BY \u3067\u306F v3.0.0 \u4EE5\u964D\u3001\u7A7A\u30BB\u30EB\u306F 0 \u3067\u306F\u306A\u304F\u6700\u5C0F\u5024\u3068\u3057\u3066\u6271\u308F\u308C\u307E\u3059 \u2014 \xA76\u300C\u578B\u4ED8\u304D\u6BD4\u8F03\u300D\u53C2\u7167\uFF09\u3002\r\n\r\n> **\u306A\u304A\u3001\u30D5\u30A3\u30FC\u30EB\u30C9\u5024\u305D\u306E\u3082\u306E\u306F\u7121\u50B7\u3067\u3059\u3002** kSQL \u306F\u53D6\u5F97\u3057\u305F\u6570\u5024\u3092\u6587\u5B57\u5217\u306E\u307E\u307E\u4FDD\u6301\u3057\u3001\u7B97\u8853\u5F0F\u3092\u901A\u3055\u306A\u3044\u9650\u308A\u6700\u592730\u6841\u3092\u6709\u965010\u9032\u3068\u3057\u3066\u53B3\u5BC6\u6BD4\u8F03\u3057\u307E\u3059\u3002`1.10 = 1.1`\u3001`-0 = 0`\u3001`1e21 = 1000000000000000000000`\u3067\u3059\u3002JS\u7B97\u8853\u30FBSUM/AVG\u30FB\u6570\u5024\u95A2\u6570\u304C\u8FD4\u3059\u5024\u306F\u3001\u65E2\u306Bbinary64\u3078\u4E38\u3081\u3089\u308C\u305F `String(number)` \u306E10\u9032\u5024\u3068\u3057\u3066\u6BD4\u8F03\u3057\u307E\u3059\u3002\r\n\r\n---", uri: "ksql://language-reference/03-arithmetic-expressions" }, "04-case-when": { heading: "4. CASE WHEN", text: "## 4. CASE WHEN\r\n\r\n\u6761\u4EF6\u5206\u5C90\u3057\u305F\u5024\u3092\u8FD4\u3057\u307E\u3059\u3002SELECT \u5217\u30FBWHERE \u53E5\u30FBUPDATE SET \u3067\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nCASE\r\n WHEN \u6761\u4EF61 THEN \u50241\r\n WHEN \u6761\u4EF62 THEN \u50242\r\n ...\r\n [ELSE \u30C7\u30D5\u30A9\u30EB\u30C8\u5024]\r\nEND [AS \u30A8\u30A4\u30EA\u30A2\u30B9]\r\n```\r\n\r\n### SELECT \u5217\u3067\u306E\u4F7F\u7528\r\n\r\n```sql\r\nSELECT\r\n \u6C0F\u540D,\r\n CASE\r\n WHEN \u91D1\u984D >= 100000 THEN '\u5927\u53E3'\r\n WHEN \u91D1\u984D >= 10000 THEN '\u4E2D\u53E3'\r\n ELSE '\u5C0F\u53E3'\r\n END AS \u9867\u5BA2\u533A\u5206\r\nFROM APP100\r\n```\r\n\r\n```sql\r\n-- THEN \u306B\u7B97\u8853\u5F0F\u30FB\u95A2\u6570\r\nSELECT\r\n CASE\r\n WHEN \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5272\u5F15' THEN ROUND(\u91D1\u984D * 0.9)\r\n ELSE \u91D1\u984D\r\n END AS \u8ACB\u6C42\u91D1\u984D\r\nFROM APP100\r\n```\r\n\r\n### WHERE \u53E5\u3067\u306E\u4F7F\u7528\r\n\r\nWHERE \u53E5\u306E\u5DE6\u8FBA\u30FB\u53F3\u8FBA\u306B CASE WHEN \u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\uFF08FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\uFF09\u3002\r\n\r\n```sql\r\n-- \u5DE6\u8FBA: \u533A\u5206\u306B\u5FDC\u3058\u3066\u6BD4\u8F03\u5024\u3092\u5207\u308A\u66FF\u3048\r\nWHERE CASE\r\n WHEN \u533A\u5206 = '\u7279\u5225' THEN \u91D1\u984D\r\n ELSE 0\r\n END > 1000\r\n\r\n-- \u53F3\u8FBA: \u533A\u5206\u3054\u3068\u306B\u95BE\u5024\u3092\u5909\u3048\u308B\r\nWHERE \u30B9\u30B3\u30A2 > CASE\r\n WHEN \u30E9\u30F3\u30AF = 'A' THEN 80\r\n ELSE 50\r\n END\r\n```\r\n\r\n### UPDATE SET \u3067\u306E\u4F7F\u7528\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u9867\u5BA2\u30E9\u30F3\u30AF = CASE\r\n WHEN \u91D1\u984D >= 100000 THEN 'S'\r\n WHEN \u91D1\u984D >= 10000 THEN 'A'\r\n ELSE 'B'\r\n END\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5BFE\u8C61'\r\n```\r\n\r\nTHEN / ELSE \u306B\u914D\u5217\u30EA\u30C6\u30E9\u30EB\u3092\u6307\u5B9A\u3059\u308B\u3068\u3001\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u306B\u5FDC\u3058\u3066\u30E6\u30FC\u30B6\u30FC\u9078\u629E\u30FB\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u7B49\u306B\u66F8\u304D\u8FBC\u3081\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E: \u30B9\u30C6\u30FC\u30BF\u30B9\u306B\u5FDC\u3058\u3066\u62C5\u5F53\u8005\u3092\u5207\u308A\u66FF\u3048\r\nUPDATE APP89\r\nSET \u62C5\u5F53\u8005 = CASE\r\n WHEN \u512A\u5148\u5EA6 = '\u9AD8' THEN ['user1', 'user2']\r\n ELSE 'user3'\r\n END\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u672A\u7740\u624B'\r\n\r\n-- \u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9: IF() \u77ED\u7E2E\u8A18\u6CD5\r\nUPDATE APP89\r\nSET \u30BF\u30B0 = IF(\u9867\u5BA2\u30E9\u30F3\u30AF = 'A', ['\u91CD\u8981', 'VIP'], '\u901A\u5E38')\r\nWHERE \u62C5\u5F53\u8005 = 'user1'\r\n```\r\n\r\n### \u5171\u901A\u30EB\u30FC\u30EB\r\n\r\n- THEN / ELSE \u306E\u5024\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u30FB\u6570\u5024\u30FB\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u30FB\u7B97\u8853\u5F0F\u30FB\u95A2\u6570\u547C\u3073\u51FA\u3057\u30FB**\u914D\u5217\u30EA\u30C6\u30E9\u30EB `[...]`** \u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\r\n- ELSE \u3092\u7701\u7565\u3059\u308B\u3068\u3001\u3069\u306E\u6761\u4EF6\u306B\u3082\u5408\u81F4\u3057\u306A\u3044\u5834\u5408\u306B\u7A7A\u6587\u5B57\uFF08NULL \u76F8\u5F53\uFF09\u3092\u8FD4\u3057\u307E\u3059\r\n- IF(\u6761\u4EF6, then\u5024, else\u5024) \u306F CASE WHEN \u306E\u77ED\u7E2E\u8A18\u6CD5\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u3059\r\n- \u914D\u5217\u30EA\u30C6\u30E9\u30EB\u3092 THEN/ELSE \u3067\u8FD4\u3059\u5834\u5408\u3001\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u306B\u5FDC\u3058\u3066\u81EA\u52D5\u5909\u63DB\u3055\u308C\u307E\u3059\uFF08INSERT VALUES / UPDATE SET\uFF09\r\n\r\n### WHEN \u6761\u4EF6\u306E\u8A55\u4FA1\r\n\r\n`WHEN` \u306E\u6761\u4EF6\u306B\u306F `WHERE` \u3068\u540C\u3058\u8FF0\u8A9E\u3092\u66F8\u3051\u307E\u3059\uFF08\u6BD4\u8F03 `= != < >`\u30FB`IN`\uFF0F`NOT IN`\u30FB`LIKE`\u30FB`BETWEEN`\u30FB`AND`\uFF0F`OR`\uFF0F`NOT` \u7B49\uFF09\u3002**`WHERE` \u3068\u540C\u3058\u8FF0\u8A9E\u69CB\u6587\u3067\u3001kSQL \u306E\u540C\u3058\u4E8C\u5024\u8A55\u4FA1\u898F\u5247\u306B\u3088\u308A\u884C\u3054\u3068\u306B\u8A55\u4FA1**\u3055\u308C\u3001`IN` \u306E\u4E00\u81F4\u898F\u5247\u3082 \xA76 \u3068\u540C\u4E00\u3067\u3059\uFF08\u8907\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u300C\u3044\u305A\u308C\u304B\u3092\u542B\u3080\u300D\u5224\u5B9A\u306A\u3069\uFF09\u3002\r\n\r\n```sql\r\nSELECT $id,\r\n CASE WHEN \u533A\u5206 IN ('A', 'B') THEN '\u5BFE\u8C61' ELSE '\u5BFE\u8C61\u5916' END AS \u5224\u5B9A,\r\n CASE WHEN \u30BF\u30B0 IN ('\u91CD\u8981') THEN 1 ELSE 0 END AS \u91CD\u8981\u30D5\u30E9\u30B0 -- \u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\uFF1D\u300C\u542B\u3080\u300D\u5224\u5B9A\r\nFROM APP100\r\n```\r\n\r\n- CASE / IF \u306F**\u5E38\u306B JavaScript \u3067\u8A55\u4FA1**\u3055\u308C\uFF08kintone \u3078\u306F\u62BC\u3057\u4E0B\u3052\u307E\u305B\u3093\uFF09\u3001\u6761\u4EF6\u306F FULL_SCAN \u3068\u540C\u3058\u898F\u5247\u3067\u5224\u5B9A\u3057\u307E\u3059\u3002\r\n- \u3057\u305F\u304C\u3063\u3066\u3001\u9078\u629E\u7CFB\u30D5\u30A3\u30FC\u30EB\u30C9\u306B**\u5B9A\u7FA9\u306B\u7121\u3044\u9078\u629E\u80A2\u5024**\u3092 `WHEN \u2026 IN (\u2026)` \u3078\u6E21\u3057\u3066\u3082\u3001`WHERE` \u304C REST \u306B\u62BC\u3057\u4E0B\u3052\u3089\u308C\u3066 `GAIA_IQ10` \u306B\u306A\u308A\u5F97\u308B\u306E\u3068\u9055\u3044\u3001CASE \u306E\u6761\u4EF6\u306F\u5E38\u306B\u30ED\u30FC\u30AB\u30EB\u8A55\u4FA1\u306A\u306E\u3067**\u30A8\u30E9\u30FC\u306B\u306A\u3089\u305A\u5358\u306B\u4E0D\u4E00\u81F4**\u306B\u306A\u308A\u307E\u3059\uFF08\xA76 \u306E\u300C\u5B9A\u7FA9\u306B\u7121\u3044\u9078\u629E\u80A2\u5024\u300D\u306E\u6CE8\u610F\u3092\u53C2\u7167\uFF09\u3002\r\n\r\n---", uri: "ksql://language-reference/04-case-when" }, "05-string-number-functions": { heading: "5. \u6587\u5B57\u5217\u30FB\u6570\u5024\u95A2\u6570", text: "## 5. \u6587\u5B57\u5217\u30FB\u6570\u5024\u95A2\u6570\r\n\r\n\u95A2\u6570\u306F SELECT \u5217\u30FBWHERE \u5DE6\u8FBA\u30FBORDER BY\u30FBCASE WHEN \u306E THEN/ELSE \u3067\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002 \r\n\u95A2\u6570\u306E\u7D50\u679C\u306F\u7B97\u8853\u5F0F\u306E\u88AB\u6F14\u7B97\u5B50\u3068\u3057\u3066\u3082\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n### \u6587\u5B57\u5217\u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u69CB\u6587 | \u8AAC\u660E |\r\n|------|------|------|\r\n| `UPPER` | `UPPER(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5927\u6587\u5B57\u5909\u63DB |\r\n| `LOWER` | `LOWER(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5C0F\u6587\u5B57\u5909\u63DB |\r\n| `TRIM` | `TRIM(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u524D\u5F8C\u306E\u7A7A\u767D\u3092\u9664\u53BB |\r\n| `LTRIM` | `LTRIM(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5DE6\u5074\u306E\u7A7A\u767D\u3092\u9664\u53BB |\r\n| `RTRIM` | `RTRIM(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u53F3\u5074\u306E\u7A7A\u767D\u3092\u9664\u53BB |\r\n| `LENGTH` | `LENGTH(\u30D5\u30A3\u30FC\u30EB\u30C9)` | UTF-16 \u30B3\u30FC\u30C9\u30E6\u30CB\u30C3\u30C8\u6570\uFF08kintone \u306E\u6587\u5B57\u6570\uFF09\u3092\u8FD4\u3059 |\r\n| `LENGTH_CHAR` | `LENGTH_CHAR(\u30D5\u30A3\u30FC\u30EB\u30C9)` | Unicode \u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u6570\u3092\u8FD4\u3059 |\r\n| `SUBSTRING` | `SUBSTRING(\u30D5\u30A3\u30FC\u30EB\u30C9, \u958B\u59CB [, \u9577\u3055])` | \u90E8\u5206\u6587\u5B57\u5217\uFF081-indexed\u3001`SUBSTR` \u3082\u53EF\uFF09 |\r\n| `LEFT` | `LEFT(\u5024, \u6587\u5B57\u6570)` | \u5148\u982D\u304B\u3089\u6307\u5B9A\u6587\u5B57\u6570\u3092\u8FD4\u3059 |\r\n| `RIGHT` | `RIGHT(\u5024, \u6587\u5B57\u6570)` | \u672B\u5C3E\u304B\u3089\u6307\u5B9A\u6587\u5B57\u6570\u3092\u8FD4\u3059 |\r\n| `INSTR` | `INSTR(\u5024, \u691C\u7D22\u6587\u5B57\u5217)` | \u691C\u7D22\u4F4D\u7F6E\u3092 1-indexed \u3067\u8FD4\u3059\uFF08\u898B\u3064\u304B\u3089\u306A\u3051\u308C\u3070 `0`\uFF09 |\r\n| `CONCAT` | `CONCAT(\u50241, \u50242, ...)` | \u6587\u5B57\u5217\u306E\u9023\u7D50\uFF08\u53EF\u5909\u9577\u5F15\u6570\uFF09 |\r\n| `REPLACE` | `REPLACE(\u30D5\u30A3\u30FC\u30EB\u30C9, \u691C\u7D22, \u7F6E\u63DB)` | \u6587\u5B57\u5217\u7F6E\u63DB |\r\n| `REGEXP_LIKE` | `REGEXP_LIKE(\u5024, \u30D1\u30BF\u30FC\u30F3 [, \u30D5\u30E9\u30B0])` | \u4E00\u81F4\u3059\u308C\u3070\u6587\u5B57\u5217 `'1'`\u3001\u975E\u4E00\u81F4\u306A\u3089\u6587\u5B57\u5217 `'0'` |\r\n| `REGEXP_REPLACE` | `REGEXP_REPLACE(\u5024, \u30D1\u30BF\u30FC\u30F3, \u7F6E\u63DB [, \u30D5\u30E9\u30B0 [, occurrence]])` | \u6B63\u898F\u8868\u73FE\u306B\u4E00\u81F4\u3059\u308B\u7B87\u6240\u306E\u5168\u90E8\u307E\u305F\u306F N \u756A\u76EE\u3092\u7F6E\u63DB |\r\n| `REGEXP_SUBSTR` | `REGEXP_SUBSTR(\u5024, \u30D1\u30BF\u30FC\u30F3 [, \u30D5\u30E9\u30B0])` | \u6700\u521D\u306E\u4E00\u81F4\u6587\u5B57\u5217\uFF08\u975E\u4E00\u81F4\u306F\u7A7A\u6587\u5B57\uFF09 |\r\n| `TRANSLATE` | `TRANSLATE(\u5024, \u5909\u63DB\u5143, \u5909\u63DB\u5148)` | \u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u5358\u4F4D\u306E 1 \u6587\u5B57\u5BFE 1 \u6587\u5B57\u5199\u50CF |\r\n| `COALESCE` | `COALESCE(\u50241, \u50242, ...)` | \u6700\u521D\u306E\u975E\u7A7A\u5024\u3092\u8FD4\u3059 |\r\n| `ISNULL` | `ISNULL(\u5024, \u4EE3\u66FF\u5024)` | \u5024\u304C\u7A7A\u306A\u3089\u4EE3\u66FF\u5024\u3001\u305D\u308C\u4EE5\u5916\u306F\u5024\uFF08`COALESCE` \u306E 2 \u5F15\u6570\u7248\uFF09 |\r\n| `NULLIF` | `NULLIF(\u50241, \u50242)` | \u50241 \u3068 \u50242 \u304C\u7B49\u3057\u3051\u308C\u3070\u7A7A\u6587\u5B57\u3001\u305D\u308C\u4EE5\u5916\u306F \u50241 |\r\n| `GREATEST` | `GREATEST(\u50241, \u50242, ...)` | \u884C\u5185\u306E\u6700\u5927\u5024\uFF082 \u5F15\u6570\u4EE5\u4E0A\uFF09 |\r\n| `LEAST` | `LEAST(\u50241, \u50242, ...)` | \u884C\u5185\u306E\u6700\u5C0F\u5024\uFF082 \u5F15\u6570\u4EE5\u4E0A\uFF09 |\r\n| `LPAD` | `LPAD(\u5024, \u9577\u3055 [, \u57CB\u3081\u6587\u5B57\u5217])` | \u5DE6\u5074\u3092\u57CB\u3081\u308B\uFF08\u65E2\u5B9A\u306F\u534A\u89D2\u30B9\u30DA\u30FC\u30B9\uFF09 |\r\n| `RPAD` | `RPAD(\u5024, \u9577\u3055 [, \u57CB\u3081\u6587\u5B57\u5217])` | \u53F3\u5074\u3092\u57CB\u3081\u308B\uFF08\u65E2\u5B9A\u306F\u534A\u89D2\u30B9\u30DA\u30FC\u30B9\uFF09 |\r\n\r\n```sql\r\nSELECT UPPER(\u30B9\u30C6\u30FC\u30BF\u30B9) AS \u30B9\u30C6\u30FC\u30BF\u30B9 FROM APP100\r\nSELECT CONCAT(\u59D3, '\u3000', \u540D) AS \u6C0F\u540D FROM APP100\r\nSELECT '\u6C0F\u540D: ' || \u59D3 || '\u3000' || \u540D AS \u8868\u793A FROM APP100 -- || \u306F CONCAT \u3068\u540C\u7FA9\uFF08v3.4.0\uFF09\r\nSELECT SUBSTRING(\u90F5\u4FBF\u756A\u53F7, 1, 3) AS \u5E02\u5916\u5C40\u756A FROM APP100\r\nSELECT LEFT(\u9867\u5BA2\u30B3\u30FC\u30C9, 2) AS \u5206\u985E, RIGHT(\u9867\u5BA2\u30B3\u30FC\u30C9, 4) AS \u9023\u756A FROM APP100\r\nSELECT LPAD(\u9867\u5BA2No, 5, '0') AS \u9867\u5BA2\u30B3\u30FC\u30C9 FROM APP100\r\nSELECT GREATEST(\u898B\u7A4D\u984D, \u53D7\u6CE8\u984D, \u8ACB\u6C42\u984D) AS \u6700\u5927\u984D FROM APP100\r\nSELECT REPLACE(\u96FB\u8A71\u756A\u53F7, '-', '') AS \u96FB\u8A71\u756A\u53F7 FROM APP100\r\nSELECT REGEXP_LIKE(\u90F5\u4FBF\u756A\u53F7, '^[0-9]{3}-[0-9]{4}$') AS \u66F8\u5F0FOK FROM APP100\r\nSELECT REGEXP_REPLACE(\u96FB\u8A71\u756A\u53F7, '[^0-9]', '') AS \u6570\u5B57\u306E\u307F FROM APP100\r\nSELECT REGEXP_SUBSTR(\u30E1\u30E2, '[A-Z]{2}-[0-9]{6}') AS \u53D7\u4ED8\u756A\u53F7 FROM APP100\r\nSELECT LENGTH(\u4F1A\u793E\u540D) AS kintone\u6587\u5B57\u6570, LENGTH_CHAR(\u4F1A\u793E\u540D) AS \u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u6570 FROM APP100\r\nSELECT TRANSLATE(\u4F1A\u793E\u540D, '\u555E\u7130\u9DD7', '\u5516\u7114\u9D0E') AS \u4F1A\u793E\u540D FROM APP100\r\nSELECT COALESCE(\u30E1\u30E2, '\uFF08\u306A\u3057\uFF09') AS \u30E1\u30E2 FROM APP100\r\nSELECT ISNULL(\u5EFA\u7269\u540D, '\uFF08\u306A\u3057\uFF09') AS \u5EFA\u7269\u540D FROM APP100\r\nSELECT NULLIF(\u696D\u7A2E, '\u305D\u306E\u4ED6') AS \u696D\u7A2E FROM APP100 -- '\u305D\u306E\u4ED6' \u3092\u7A7A\u306B\u3059\u308B\r\n```\r\n\r\n> `SUBSTRING` \u306E\u958B\u59CB\u4F4D\u7F6E\u306F 1 \u4EE5\u4E0A\u3067\u3059\u3002`0` \u4EE5\u4E0B\u306F `1` \u3068\u540C\u3058\u304F\u5148\u982D\u304B\u3089\u6271\u3044\u307E\u3059\u3002MySQL \u306E\u3088\u3046\u306A\u300C\u8CA0\u6570\uFF1D\u672B\u5C3E\u304B\u3089\u300D\u306E\u5207\u308A\u51FA\u3057\u306B\u306F\u5BFE\u5FDC\u3057\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u672B\u5C3E\u304B\u3089\u53D6\u5F97\u3059\u308B\u5834\u5408\u306F `RIGHT` \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n`SUBSTRING` / `LEFT` / `RIGHT` / `LPAD` / `RPAD` \u306E\u9577\u3055\u5F15\u6570\u306F\u30B3\u30FC\u30C9\u30E6\u30CB\u30C3\u30C8\u4E88\u7B97\u3067\u3059\u3002\u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u3092\u5272\u308B\u5883\u754C\u3067\u306F\u5B89\u5168\u306A\u5074\u3078\u7E2E\u3081\u307E\u3059\u3002\u7D50\u679C\u306F\u5FC5\u305A\u6307\u5B9A\u4E88\u7B97\u4EE5\u4E0B\u306B\u306A\u308A\u307E\u3059\u3002`LPAD` / `RPAD` \u3067\u306F\u3001\u6307\u5B9A\u4E88\u7B97\u306E\u6B8B\u308A\u306B\u57CB\u3081\u6587\u5B57\u5217\u3092\u5B89\u5168\u306B\u53CE\u3081\u3089\u308C\u306A\u3044\u5834\u5408\u3001\u7D50\u679C\u304C\u6307\u5B9A\u9577\u3088\u308A\u77ED\u304F\u306A\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002\r\n\r\n`LENGTH` \u306F kintone \u3068\u540C\u3058 UTF-16 \u30B3\u30FC\u30C9\u30E6\u30CB\u30C3\u30C8\u6570\u3001`LENGTH_CHAR` \u306F Unicode \u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u6570\u3092\u8FD4\u3057\u307E\u3059\u3002\u305F\u3068\u3048\u3070 `LENGTH('\u{20B9F}') = 2`\u3001`LENGTH_CHAR('\u{20B9F}') = 1` \u3067\u3059\u3002`LENGTH(x) - LENGTH_CHAR(x)` \u306F\u3001\u5165\u529B\u306B\u542B\u307E\u308C\u308B\u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u6570\u306B\u306A\u308A\u307E\u3059\u3002`LENGTH_CHAR` \u306F\u66F8\u8A18\u7D20\u6570\u3067\u306F\u306A\u3044\u305F\u3081\u3001IVS\u30FB\u7D50\u5408\u6587\u5B57\u30FBZWJ \u7D75\u6587\u5B57\u3092\u4EBA\u304C\u898B\u308B 1 \u6587\u5B57\u3068\u3057\u3066\u307E\u3068\u3081\u307E\u305B\u3093\u3002\r\n\r\n`TRANSLATE` \u306F `\u5909\u63DB\u5143` \u3068 `\u5909\u63DB\u5148` \u3092\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u5358\u4F4D\u3067\u4F4D\u7F6E\u5BFE\u5FDC\u3055\u305B\u308B\u30011 \u6587\u5B57\u304B\u3089 1 \u6587\u5B57\u3078\u306E\u5199\u50CF\u5C02\u7528\u95A2\u6570\u3067\u3059\u3002\u4E21\u8005\u306E\u6587\u5B57\u6570\u304C\u7570\u306A\u308B\u5834\u5408\u306F `ArgumentError` \u306B\u306A\u308A\u3001`\u5909\u63DB\u5143` \u306B\u540C\u3058\u6587\u5B57\u304C\u8907\u6570\u3042\u308B\u5834\u5408\u306F\u6700\u521D\u306E\u5BFE\u5FDC\u304C\u512A\u5148\u3055\u308C\u307E\u3059\u3002\u5BFE\u5FDC\u3057\u306A\u3044\u5165\u529B\u6587\u5B57\u306F\u305D\u306E\u307E\u307E\u8FD4\u3057\u307E\u3059\u3002`\uFF8E\uFF9E`\uFF082 \u6587\u5B57\uFF09\u304B\u3089 `\u30DC`\uFF081 \u6587\u5B57\uFF09\u306E\u3088\u3046\u306A\u534A\u89D2\u30AB\u30CA\u304B\u3089\u5168\u89D2\u30AB\u30CA\u3078\u306E\u5909\u63DB\u306F 2 \u5BFE 1 \u3092\u542B\u3080\u305F\u3081\u3001`TRANSLATE` \u3060\u3051\u3067\u306F\u3067\u304D\u307E\u305B\u3093\u3002\r\n\r\n\u6B63\u898F\u8868\u73FE3\u95A2\u6570\u306F ECMAScript\uFF08JavaScript\uFF09\u65B9\u8A00\u3092\u4F7F\u3044\u3001POSIX ERE \u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30D5\u30E9\u30B0\u306F `i` / `m` / `s` \u306E\u307F\u6307\u5B9A\u3067\u304D\u3001Unicode \u30E2\u30FC\u30C9 `u` \u306F\u5E38\u306B\u6709\u52B9\u3067\u3059\u3002`g` / `y` / `d` / `u` / `v` \u305D\u306E\u4ED6\u306E\u30D5\u30E9\u30B0\u306F `ArgumentError` \u306B\u306A\u308A\u307E\u3059\u3002`REGEXP_REPLACE` \u306E `occurrence` \u306F\u7701\u7565\u307E\u305F\u306F `0` \u3067\u5168\u4E00\u81F4\u3001\u975E\u8CA0\u6574\u6570 `N`\uFF081 \u4EE5\u4E0A\uFF09\u3067 N \u756A\u76EE\u306E\u4E00\u81F4\u3060\u3051\u3092\u7F6E\u63DB\u3057\u3001\u4E00\u81F4\u6570\u3092\u8D85\u3048\u308B\u5834\u5408\u306F\u5165\u529B\u3092\u5909\u66F4\u3057\u307E\u305B\u3093\u3002kSQL \u3067\u306F\u7B2C4\u5F15\u6570\u304C\u30D5\u30E9\u30B0\u3001\u7B2C5\u5F15\u6570\u304C `occurrence` \u3067\u3042\u308A\u3001MySQL\uFF0FOracle \u3068\u306F\u5F15\u6570\u4F4D\u7F6E\u304C\u7570\u306A\u308A\u307E\u3059\u3002\u7F6E\u63DB\u6587\u5B57\u5217\u306E `$1`\u301C`$99`\u30FB`$`\u30FB`$&`\u30FB`$$` \u306F ECMAScript \u306E\u898F\u5247\u3067\u89E3\u91C8\u3057\u307E\u3059\u3002\u524D\u5F8C\u6587\u5B57\u5217\u3092\u633F\u5165\u3059\u308B `` $` `` \u3068 `$'` \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002`REGEXP_SUBSTR` \u306F\u975E\u4E00\u81F4\u3068\u7A7A\u6587\u5B57\u4E00\u81F4\u306E\u3069\u3061\u3089\u3082\u7A7A\u6587\u5B57\u3092\u8FD4\u3059\u305F\u3081\u3001\u533A\u5225\u304C\u5FC5\u8981\u306A\u5834\u5408\u306F `REGEXP_LIKE` \u3092\u4F75\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u30D1\u30BF\u30FC\u30F3\u3001\u30D5\u30E9\u30B0\u3001`occurrence` \u306B\u306F\u30EA\u30C6\u30E9\u30EB\u3060\u3051\u3067\u306A\u304F\u5F0F\u3084\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u6307\u5B9A\u3067\u304D\u3001\u884C\u3054\u3068\u306B\u5B9F\u884C\u6642\u8A55\u4FA1\u3055\u308C\u307E\u3059\u3002\r\n\r\n> **\u6B63\u898F\u8868\u73FE\u306E\u5229\u7528\u306F\u30E6\u30FC\u30B6\u30FC\u8CAC\u4EFB\u3067\u3059\u3002** \u30D1\u30BF\u30FC\u30F3\u306B\u3088\u3063\u3066\u306F ReDoS\uFF08\u7834\u6EC5\u7684\u30D0\u30C3\u30AF\u30C8\u30E9\u30C3\u30AF\uFF09\u3067\u5B9F\u884C\u304C\u66B4\u8D70\u3057\u3001kSQL \u304B\u3089\u306F\u4E2D\u65AD\u3067\u304D\u307E\u305B\u3093\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306F\u30BF\u30D6\u3092\u5F37\u5236\u7D42\u4E86\uFF08\u540C\u3058\u30BF\u30D6\u306E\u672A\u4FDD\u5B58\u30EC\u30B3\u30FC\u30C9\u7DE8\u96C6\u3068\u672A\u4FDD\u5B58 SQL \u3082\u5931\u308F\u308C\u307E\u3059\uFF09\u3001CLI \u3067\u306F Ctrl+C\u3001MCP \u3067\u306F\u30D7\u30ED\u30BB\u30B9\u3092\u518D\u8D77\u52D5\u3057\u3066\u304F\u3060\u3055\u3044\u3002MCP \u3067\u306F\u540C\u4E00\u30D7\u30ED\u30BB\u30B9\u306E\u4ED6\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u3082\u505C\u6B62\u3057\u307E\u3059\u3002\r\n>\r\n> \u7D50\u679C\u3084\u69CB\u6587\u306E\u53D7\u7406\u53EF\u5426\u306F\u5B9F\u884C\u74B0\u5883\uFF08\u30D6\u30E9\u30A6\u30B6\uFF0FNode\uFF09\u3068\u305D\u306E\u7248\u306B\u4F9D\u5B58\u3057\u5F97\u307E\u3059\u3002\u7279\u306B `\\p{}`\u3001`u+i` \u306E case folding \u306F Unicode \u7248\u5DEE\u3001\u65B0\u3057\u3044\u6B63\u898F\u8868\u73FE\u69CB\u6587\u306F Node \u7248\u5DEE\u306E\u5F71\u97FF\u3092\u53D7\u3051\u3001\u540C\u3058 SQL \u3067\u3082\u30D7\u30E9\u30B0\u30A4\u30F3\u30FBCLI\u30FBMCP \u3067\u7D50\u679C\u304C\u5909\u308F\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\r\n\r\n`GREATEST` / `LEAST` \u306F\u3001\u5217\u65B9\u5411\u306E\u96C6\u7D04\u95A2\u6570 `MAX` / `MIN` \u3068\u306F\u7570\u306A\u308A\u3001\u540C\u3058\u884C\u306E\u5F15\u6570\u540C\u58EB\u3092\u6BD4\u8F03\u3057\u307E\u3059\u3002\u7A7A\u6587\u5B57\u306F\u5E38\u306B\u6700\u5C0F\u3067\u3059\u3002\u7A7A\u6587\u5B57\u3092\u9664\u3044\u305F\u96C6\u5408\u304C\u3059\u3079\u3066\u6570\u5024\u306A\u3089\u6570\u5024\u6BD4\u8F03\u3057\u30011 \u3064\u3067\u3082\u975E\u6570\u5024\u306A\u3089\u96C6\u5408\u5168\u4F53\u3092\u6587\u5B57\u5217\u6BD4\u8F03\u3057\u307E\u3059\u3002\u6570\u5024\u304C\u540C\u5024\u306A\u3089\u5143\u306E\u6587\u5B57\u5217\u8868\u8A18\u3092\u4E8C\u6B21\u30AD\u30FC\u306B\u3059\u308B\u305F\u3081\u3001\u5F15\u6570\u9806\u306B\u3088\u3063\u3066\u7D50\u679C\u306F\u5909\u308F\u308A\u307E\u305B\u3093\u3002\r\n\r\n`LEFT` / `RIGHT` / `INSTR` / `GREATEST` / `LEAST` / `LPAD` / `RPAD` \u306F\u5F15\u6570\u306E\u500B\u6570\u3092\u691C\u8A3C\u3057\u3001\u4E0D\u6B63\u306A\u5834\u5408\u306F `ArgumentError` \u306B\u306A\u308A\u307E\u3059\u3002`LPAD` / `RPAD` \u3067\u57CB\u3081\u6587\u5B57\u5217\u304C\u7A7A\u306E\u5834\u5408\u306F\u3001\u5165\u529B\u5024\u3092\u305D\u306E\u307E\u307E\u8FD4\u3057\u307E\u3059\u3002\r\n\r\n- `LENGTH_CHAR` / `TRANSLATE` / `REGEXP_LIKE` / `REGEXP_REPLACE` / `REGEXP_SUBSTR` / `INSTR` / `GREATEST` / `LEAST` / `LPAD` / `RPAD` \u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F `` `REGEXP_LIKE` `` \u306E\u3088\u3046\u306B\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\u3002`LEFT` / `RIGHT` \u306F `LEFT JOIN` / `RIGHT JOIN` \u306E\u4E88\u7D04\u8A9E\u3092\u517C\u306D\u3066\u304A\u308A\u3001\u76F4\u5F8C\u306B `(` \u304C\u3042\u308B\u5834\u5408\u306E\u307F\u95A2\u6570\u3068\u3057\u3066\u6271\u3044\u307E\u3059\u3002\r\n\r\n> **`ISNULL` \u306F 2 \u5F15\u6570\uFF08SQL Server \u7CFB\uFF09\u3067\u3059\u3002** MySQL \u306E 1 \u5F15\u6570 `ISNULL(\u5F0F)`\uFF08\u771F\u507D\u3092\u8FD4\u3059\uFF09\u3068\u306F**\u5225\u7269**\u3067\u3059\u3002\u7A7A\u5224\u5B9A\u306B\u306F `IS NULL` / `IS NOT NULL`\uFF08\u2192 [\xA76](#6-where-\u53E5)\uFF09\u3092\u4F7F\u3063\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n> **`NULLIF` \u306B\u3088\u308B\u30BC\u30ED\u9664\u7B97\u30AC\u30FC\u30C9\u306F\u52B9\u304D\u307E\u305B\u3093\u3002** kintone \u306B\u306F NULL \u304C\u306A\u304F kSQL \u3067\u306F**\u7A7A\u6587\u5B57\u304C NULL \u76F8\u5F53**\u306E\u305F\u3081\u3001`NULLIF(x, 0)` \u306E\u7D50\u679C\uFF08\u7A7A\u6587\u5B57\uFF09\u3092\u9664\u6570\u306B\u3059\u308B\u3068 `Number('') = 0` \u3068\u306A\u308A\u3001\u7D50\u5C40\u30BC\u30ED\u9664\u7B97\u3067 `NaN` \u306B\u306A\u308A\u307E\u3059\u3002\r\n>\r\n> ```sql\r\n> -- \u2717 RDB \u306E\u5B9A\u756A\u3060\u304C kSQL \u3067\u306F NaN\uFF08\u30AC\u30FC\u30C9\u306B\u306A\u3089\u306A\u3044\uFF09\r\n> SELECT 1000 / NULLIF(\u91D1\u984D, 0) AS \u5358\u4FA1 FROM APP100 -- \u91D1\u984D=0 \u306E\u884C\u306F NaN\r\n>\r\n> -- \u25CB NULL \u7F6E\u63DB\u3068\u3057\u3066\u306F\u6B63\u3057\u304F\u6A5F\u80FD\u3059\u308B\r\n> SELECT ISNULL(NULLIF(\u91D1\u984D, 0), '\u672A\u8A2D\u5B9A') AS \u91D1\u984D FROM APP100 -- \u91D1\u984D=0 \u306E\u884C\u306F\u300C\u672A\u8A2D\u5B9A\u300D\r\n>\r\n> -- \u25CB \u30BC\u30ED\u9664\u7B97\u3092\u907F\u3051\u305F\u3044\u5834\u5408\u306F CASE WHEN \u3092\u4F7F\u3046\r\n> SELECT CASE WHEN \u91D1\u984D = 0 THEN '' ELSE 1000 / \u91D1\u984D END AS \u5358\u4FA1 FROM APP100\r\n> ```\r\n\r\n### \u6570\u5024\u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u69CB\u6587 | \u8AAC\u660E |\r\n|------|------|------|\r\n| `ROUND` | `ROUND(\u30D5\u30A3\u30FC\u30EB\u30C9 [, \u6841])` | \u56DB\u6368\u4E94\u5165 |\r\n| `FLOOR` | `FLOOR(\u30D5\u30A3\u30FC\u30EB\u30C9 [, \u6841])` | \u5207\u308A\u6368\u3066 |\r\n| `CEIL` | `CEIL(\u30D5\u30A3\u30FC\u30EB\u30C9 [, \u6841])` | \u5207\u308A\u4E0A\u3052\uFF08`CEILING` \u3082\u53EF\uFF09 |\r\n| `TRUNCATE` | `TRUNCATE(\u30D5\u30A3\u30FC\u30EB\u30C9 [, \u6841])` | 0 \u65B9\u5411\u3078\u5207\u308A\u6368\u3066\uFF08`TRUNC` \u3082\u53EF\uFF09 |\r\n\r\n\u6841\u6570\u306E\u6307\u5B9A:\r\n- \u6B63\u306E\u6574\u6570: \u5C0F\u6570\u70B9\u4EE5\u4E0B n \u6841\u3067\u4E38\u3081\u308B\r\n- `0`\uFF08\u7701\u7565\u6642\uFF09: \u6574\u6570\u306B\u4E38\u3081\u308B\r\n- \u8CA0\u306E\u6574\u6570: 10^n \u306E\u5358\u4F4D\u3067\u4E38\u3081\u308B\r\n\r\n```sql\r\nSELECT ROUND(\u91D1\u984D, 2) AS \u91D1\u984D FROM APP100 -- \u4F8B: 1234.567 \u2192 1234.57\r\nSELECT ROUND(\u91D1\u984D) AS \u91D1\u984D FROM APP100 -- \u4F8B: 1234.5 \u2192 1235\r\nSELECT ROUND(\u91D1\u984D, -3) AS \u5343\u5358\u4F4D FROM APP100 -- \u4F8B: 1234567 \u2192 1235000\r\nSELECT FLOOR(\u91D1\u984D, -2) AS \u767E\u672A\u6E80\u5207\u6368 FROM APP100\r\nSELECT TRUNCATE(\u91D1\u984D, 2) AS \u5C0F\u65702\u6841\u5207\u6368 FROM APP100\r\n```\r\n\r\n`FLOOR` \u304C\u5E38\u306B\u5C0F\u3055\u3044\u65B9\u3078\u4E38\u3081\u308B\u306E\u306B\u5BFE\u3057\u3001`TRUNCATE` \u306F 0 \u65B9\u5411\u3078\u4E38\u3081\u307E\u3059\u3002\u8CA0\u6570\u3067\u5DEE\u304C\u51FA\u307E\u3059\uFF08`FLOOR(-1.5)` = `-2`\u3001`TRUNCATE(-1.5)` = `-1`\uFF09\u3002\r\n\r\n- `TRUNCATE` / `TRUNC` \u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F `` `TRUNCATE` `` \u3068\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\u3002\r\n\r\n### \u6570\u5B66\u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u69CB\u6587 | \u8AAC\u660E |\r\n|------|------|------|\r\n| `ABS` | `ABS(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u7D76\u5BFE\u5024 |\r\n| `MOD` | `MOD(\u30D5\u30A3\u30FC\u30EB\u30C9, \u9664\u6570)` | \u5270\u4F59\uFF08`%` \u6F14\u7B97\u5B50\u3068\u540C\u7B49\uFF09 |\r\n| `POWER` | `POWER(\u30D5\u30A3\u30FC\u30EB\u30C9, \u6307\u6570)` | \u7D2F\u4E57\uFF08`POW` \u3082\u53EF\uFF09 |\r\n| `SQRT` | `SQRT(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5E73\u65B9\u6839 |\r\n\r\n```sql\r\nSELECT ABS(\u5DEE\u984D) AS \u5DEE\u984D\u7D76\u5BFE\u5024 FROM APP100\r\nSELECT MOD(\u6570\u91CF, 3) AS \u4F59\u308A FROM APP100 -- \u6570\u91CF % 3 \u3068\u540C\u7B49\r\nSELECT POWER(\u8FBA\u9577, 2) AS \u9762\u7A4D FROM APP100\r\nSELECT ROUND(SQRT(\u9762\u7A4D), 2) AS \u8FBA\u9577 FROM APP100\r\n```\r\n\r\n### FORMAT \u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u69CB\u6587 | \u8AAC\u660E |\r\n|------|------|------|\r\n| `FORMAT` | `FORMAT(\u30D5\u30A3\u30FC\u30EB\u30C9, \u30D1\u30BF\u30FC\u30F3)` | \u66F8\u5F0F\u6574\u5F62 |\r\n\r\n\u30D1\u30BF\u30FC\u30F3\u306B\u306F Excel \u98A8\u306E\u66F8\u5F0F\u6587\u5B57\u5217\u307E\u305F\u306F\u6574\u6570\uFF08MySQL \u30B9\u30BF\u30A4\u30EB\uFF09\u3092\u6307\u5B9A\u3057\u307E\u3059\u3002\r\n\r\n| \u30D1\u30BF\u30FC\u30F3 | \u5165\u529B | \u51FA\u529B |\r\n|---------|------|------|\r\n| `'#,##0'` | 1234567 | `1,234,567` |\r\n| `'#,##0.00'` | 1234.5 | `1,234.50` |\r\n| `'0.00'` | 1234.5 | `1234.50` |\r\n| `'0.00%'` | 0.156 | `15.60%` |\r\n| `'#,##0.##'` | 1234.5 | `1,234.5` |\r\n| `2`\uFF08\u6574\u6570\uFF09 | 1234.5 | `1,234.50` |\r\n\r\n```sql\r\nSELECT FORMAT(\u91D1\u984D, '#,##0') AS \u91D1\u984D\u8868\u793A FROM APP100\r\nSELECT FORMAT(\u9054\u6210\u7387, '0.00%') AS \u9054\u6210\u7387\u8868\u793A FROM APP100\r\n```\r\n\r\n### \u578B\u5909\u63DB\u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u69CB\u6587 | \u8AAC\u660E |\r\n|------|------|------|\r\n| `CAST` | `CAST(\u30D5\u30A3\u30FC\u30EB\u30C9 AS \u578B)` | \u578B\u5909\u63DB |\r\n| `CONVERT` | `CONVERT(\u30D5\u30A3\u30FC\u30EB\u30C9, \u578B)` | \u578B\u5909\u63DB\uFF08`CAST` \u306E\u5225\u8A18\u6CD5\uFF09 |\r\n\r\n> \u95A2\u6570\u30A8\u30A4\u30EA\u30A2\u30B9\u306E canonical \u5BFE\u5FDC\u306F `SUBSTR` \u2192 `SUBSTRING`\u3001`CONVERT` \u2192 `CAST`\u3001`CEILING` \u2192 `CEIL`\u3001`TRUNC` \u2192 `TRUNCATE`\u3001`POW` \u2192 `POWER` \u3067\u3059\u3002\r\n\r\n\u578B\u540D: `TEXT` / `VARCHAR` / `CHAR` \u2192 \u6587\u5B57\u5217\u3001`NUMBER` / `INT` / `INTEGER` / `DECIMAL` / `FLOAT` \u2192 \u6570\u5024\r\n\r\n```sql\r\nSELECT CAST(\u91D1\u984D AS TEXT) AS \u91D1\u984D\u6587\u5B57\u5217 FROM APP100\r\nSELECT CAST(\u30B3\u30FC\u30C9 AS NUMBER) AS \u30B3\u30FC\u30C9\u6570\u5024 FROM APP100\r\n```\r\n\r\n### \u65E5\u4ED8\u30FB\u65E5\u6642\u95A2\u6570\r\n\r\n> **`WEEK()` \u306F ISO-8601 \u56FA\u5B9A\u3067\u3059\u3002MySQL `WEEK()` \u306E\u65E2\u5B9A mode 0 \u3068\u306F\u4E92\u63DB\u6027\u304C\u306A\u304F\u3001mode \u5F15\u6570\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002** \u9031\u306F\u6708\u66DC\u59CB\u307E\u308A\u3067\u3001\u305D\u306E\u5E74\u306E\u6728\u66DC\u65E5\u3092\u542B\u3080\u9031\u304C W01 \u3067\u3059\u3002\r\n\r\n| \u95A2\u6570 | \u69CB\u6587 | \u8AAC\u660E |\r\n|------|------|------|\r\n| `YEAR` | `YEAR(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5E74\u3092\u8FD4\u3059 |\r\n| `MONTH` | `MONTH(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u6708\u3092\u8FD4\u3059\uFF081\u301C12\uFF09 |\r\n| `DAY` | `DAY(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u65E5\u3092\u8FD4\u3059\uFF081\u301C31\uFF09 |\r\n| `DAYOFWEEK` | `DAYOFWEEK(\u65E5\u4ED8)` | \u66DC\u65E5\u756A\u53F7\u3092\u8FD4\u3059\uFF081=\u65E5\u66DC\u301C7=\u571F\u66DC\uFF09 |\r\n| `QUARTER` | `QUARTER(\u65E5\u4ED8)` | \u56DB\u534A\u671F\u3092\u8FD4\u3059\uFF081\u301C3\u6708=1\u300110\u301C12\u6708=4\uFF09 |\r\n| `WEEK` | `WEEK(\u65E5\u4ED8)` | ISO-8601 \u9031\u756A\u53F7\u3092\u30BC\u30ED\u57CB\u3081\u306A\u3057\u3067\u8FD4\u3059\uFF081\u301C53\uFF09 |\r\n| `DATE_FORMAT` | `DATE_FORMAT(\u30D5\u30A3\u30FC\u30EB\u30C9, \u30D5\u30A9\u30FC\u30DE\u30C3\u30C8)` | \u65E5\u4ED8\u3092\u66F8\u5F0F\u5316 |\r\n| `DATEDIFF` | `DATEDIFF(\u65E5\u4ED81, \u65E5\u4ED82)` | \u65E5\u6570\u5DEE\uFF08\u65E5\u4ED81 \u2212 \u65E5\u4ED82\uFF09 |\r\n| `DATE_ADD` | `DATE_ADD(\u65E5\u4ED8, \u52A0\u7B97\u5024, \u5358\u4F4D)` | \u65E5\u4ED8\u52A0\u7B97\uFF08\u5358\u4F4D\u306F `'YEAR'` / `'MONTH'` / `'DAY'`\uFF09 |\r\n| `LAST_DAY` | `LAST_DAY(\u65E5\u4ED8)` | \u6708\u672B\u65E5\u3092 `YYYY-MM-DD` \u3067\u8FD4\u3059 |\r\n| `CURRENT_DATE()` | `CURRENT_DATE()` | \u4ECA\u65E5\u306E\u65E5\u4ED8\uFF08`YYYY-MM-DD`\uFF09\u3092 JS \u3067\u53D6\u5F97 |\r\n| `CURRENT_TIMESTAMP()` | `CURRENT_TIMESTAMP()` | \u73FE\u5728\u65E5\u6642\uFF08ISO 8601\uFF09\u3092 JS \u3067\u53D6\u5F97 |\r\n\r\n```sql\r\nSELECT YEAR(\u4F5C\u6210\u65E5\u6642) AS \u5E74, MONTH(\u4F5C\u6210\u65E5\u6642) AS \u6708 FROM APP100\r\nSELECT DAYOFWEEK(\u53D7\u6CE8\u65E5) AS \u66DC\u65E5\u756A\u53F7, QUARTER(\u53D7\u6CE8\u65E5) AS \u56DB\u534A\u671F FROM APP100\r\nSELECT DATE_FORMAT(\u53D7\u6CE8\u65E5, '%G-%v') AS ISO\u9031, COUNT(*) FROM APP100 GROUP BY DATE_FORMAT(\u53D7\u6CE8\u65E5, '%G-%v')\r\nSELECT DATEDIFF(TODAY(), \u671F\u9650\u65E5) AS \u6B8B\u65E5\u6570 FROM APP100\r\nSELECT DATE_FORMAT(\u4F5C\u6210\u65E5\u6642, '%Y-%m') AS \u5E74\u6708 FROM APP100\r\nSELECT DATE_ADD(\u671F\u9650\u65E5, -1, 'MONTH') AS \u524D\u6708, LAST_DAY(\u671F\u9650\u65E5) AS \u6708\u672B\u65E5 FROM APP100\r\n\r\n-- SELECT \u5217\u3067\u73FE\u5728\u65E5\u6642\u3092\u4ED8\u52A0\uFF08\u5E38\u306B JS \u8A55\u4FA1\uFF09\r\nSELECT \u9867\u5BA2\u540D, \u91D1\u984D, CURRENT_TIMESTAMP() AS \u53D6\u5F97\u65E5\u6642 FROM APP100\r\nSELECT *, CURRENT_DATE() AS \u4ECA\u65E5 FROM APP100\r\n\r\n-- WHERE \u3067\u3082\u4F7F\u7528\u53EF\u80FD\uFF08FULL_SCAN\uFF09\r\nSELECT * FROM APP100 WHERE \u4F5C\u6210\u65E5 = CURRENT_DATE()\r\n```\r\n\r\n`DATE_FORMAT` \u306F\u6B21\u306E\u6307\u5B9A\u5B50\u306B\u5BFE\u5FDC\u3057\u307E\u3059\u3002ISO \u9031\u30E9\u30D9\u30EB\u306B\u306F\u3001\u66A6\u5E74 `%Y` \u3067\u306F\u306A\u304F ISO week-year `%G` \u3092\u4F7F\u3046 **`%G-%v`** \u3092\u63A8\u5968\u3057\u307E\u3059\uFF08\u5E74\u3092\u307E\u305F\u3050\u9031\u3067 `%Y-%v` \u306F\u8AA4\u3063\u305F\u7D44\u307F\u5408\u308F\u305B\u306B\u306A\u308A\u307E\u3059\uFF09\u3002\r\n\r\n| \u6307\u5B9A\u5B50 | \u5024 |\r\n|---|---|\r\n| `%Y` | 4\u6841\u5E74 |\r\n| `%y` | 2\u6841\u5E74 |\r\n| `%m` | 2\u6841\u6708\uFF08`01`\u301C`12`\uFF09 |\r\n| `%c` | \u6708\uFF08`1`\u301C`12`\uFF09 |\r\n| `%d` | 2\u6841\u65E5\uFF08`01`\u301C`31`\uFF09 |\r\n| `%e` | \u65E5\uFF08`1`\u301C`31`\uFF09 |\r\n| `%H` | 2\u6841\u6642\uFF08`00`\u301C`23`\uFF09 |\r\n| `%i` | 2\u6841\u5206\uFF08`00`\u301C`59`\uFF09 |\r\n| `%s` | 2\u6841\u79D2\uFF08`00`\u301C`59`\uFF09 |\r\n| `%w` | \u66DC\u65E5\u756A\u53F7\uFF080=\u65E5\u66DC\u301C6=\u571F\u66DC\uFF09 |\r\n| `%a` | **kSQL \u5B9A\u7FA9**\u306E\u65E5\u672C\u8A9E\u77ED\u7E2E\u66DC\u65E5\uFF08`\u65E5`\u301C`\u571F`\u3002MySQL \u306E\u82F1\u8A9E\u77ED\u7E2E\u540D\u3068\u306F\u975E\u4E92\u63DB\uFF09 |\r\n| `%v` | ISO \u9031\u756A\u53F7\uFF08`01`\u301C`53`\uFF09 |\r\n| `%G` | ISO week-year\uFF084\u6841\uFF09 |\r\n\r\n\u65B0\u3057\u3044\u65E5\u4ED8\u8EF8\u95A2\u6570\u3068 `%w` / `%a` / `%v` / `%G` \u306F\u3001\u5148\u982D10\u6587\u5B57\u304C `YYYY-MM-DD` \u3067\u66A6\u4E0A\u5B9F\u5728\u3059\u308B\u65E5\u4ED8\u306E\u5834\u5408\u3060\u3051\u5024\u3092\u8FD4\u3057\u307E\u3059\u3002\u4E0D\u6B63\u65E5\u4ED8\u3067\u306F\u95A2\u6570\u306F\u7A7A\u6587\u5B57\u306B\u306A\u308A\u3001`DATE_FORMAT` \u306F\u65B0\u3057\u3044\u6307\u5B9A\u5B50\u3060\u3051\u3092\u7A7A\u6587\u5B57\u3078\u7F6E\u63DB\u3057\u307E\u3059\u3002\u305F\u3068\u3048\u3070 `DATE_FORMAT('2026-02-31', '%Y|%w|%G-%v')` \u306F `2026||-` \u3067\u3059\u3002\u65E2\u5B589\u6307\u5B9A\u5B50\u306F\u5F93\u6765\u3069\u304A\u308A\u6587\u5B57\u5217\u90E8\u5206\u3092\u6574\u5F62\u3057\u307E\u3059\u3002\u672A\u5BFE\u5FDC\u6307\u5B9A\u5B50\u3001\u5358\u72EC `%`\u3001`%%Y` \u306F\u5F93\u6765\u3069\u304A\u308A\u7D20\u901A\u3057\u3067\u3059\u3002\r\n\r\n`DATE_ADD` \u306E\u5358\u4F4D\u306F\u5927\u6587\u5B57\u5C0F\u6587\u5B57\u3092\u533A\u5225\u3057\u307E\u305B\u3093\u3002`YEAR` / `MONTH` / `DAY` \u4EE5\u5916\u3092\u6307\u5B9A\u3059\u308B\u3068\u3001\u30EA\u30C6\u30E9\u30EB\u30FB\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u306E\u3069\u3061\u3089\u3067\u3082\u5B9F\u884C\u6642\u306B `ArgumentError` \u306B\u306A\u308A\u307E\u3059\u3002`DATE_SUB` \u306F\u3042\u308A\u307E\u305B\u3093\u3002\u6E1B\u7B97\u306F\u52A0\u7B97\u5024\u306B\u8CA0\u6570\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08`DATE_ADD(\u671F\u9650\u65E5, -1, 'MONTH')`\uFF09\u3002\r\n\r\n- `DAYOFWEEK` / `QUARTER` / `WEEK` / `LAST_DAY` \u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F `` `WEEK` `` \u306E\u3088\u3046\u306B\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\u3002`WEEKLY` \u306E\u3088\u3046\u306A\u9577\u3044\u8B58\u5225\u5B50\u306F\u5F71\u97FF\u3092\u53D7\u3051\u307E\u305B\u3093\u3002\r\n\r\n> **`CURRENT_DATE()` / `CURRENT_TIMESTAMP()` \u306F\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002** \r\n> `()` \u304C\u3042\u308C\u3070\u95A2\u6570\u3001\u306A\u3051\u308C\u3070\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3068\u3057\u3066\u6271\u308F\u308C\u307E\u3059\u3002 \r\n> kintone \u5C02\u7528\u306E `TODAY()` / `NOW()` \u3068\u7570\u306A\u308A\u3001SELECT \u5217\u3067\u3082\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n### \u95A2\u6570\u306E\u30CD\u30B9\u30C8\r\n\r\n\u95A2\u6570\u306E\u5F15\u6570\u306B\u5225\u306E\u95A2\u6570\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT UPPER(TRIM(\u6C0F\u540D)) AS \u6C0F\u540D FROM APP100\r\nSELECT ROUND(\u91D1\u984D * 1.1, 0) AS \u7A0E\u8FBC\u91D1\u984D FROM APP100\r\n```\r\n\r\n---", uri: "ksql://language-reference/05-string-number-functions" }, "06-where": { heading: "6. WHERE \u53E5", text: "## 6. WHERE \u53E5\r\n\r\n### \u6BD4\u8F03\u6F14\u7B97\u5B50\r\n\r\n| \u6F14\u7B97\u5B50 | \u610F\u5473 |\r\n|--------|------|\r\n| `=` | \u7B49\u3057\u3044 |\r\n| `!=` \u307E\u305F\u306F `<>` | \u7B49\u3057\u304F\u306A\u3044 |\r\n| `>` | \u3088\u308A\u5927\u304D\u3044 |\r\n| `<` | \u3088\u308A\u5C0F\u3055\u3044 |\r\n| `>=` | \u4EE5\u4E0A |\r\n| `<=` | \u4EE5\u4E0B |\r\n| `KLIKE` | kintone \u306E\u30AD\u30FC\u30EF\u30FC\u30C9\u3092\u542B\u3080 |\r\n| `NOT KLIKE` | kintone \u306E\u30AD\u30FC\u30EF\u30FC\u30C9\u3092\u542B\u307E\u306A\u3044 |\r\n\r\n```sql\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5B8C\u4E86'\r\nWHERE \u91D1\u984D >= 100000\r\nWHERE \u62C5\u5F53\u8005 != '\u5C71\u7530'\r\n```\r\n\r\n> \u53F3\u8FBA\u306E\u5024\u306B\u306F\u30D0\u30C3\u30C1\u5909\u6570 `@\u540D\u524D` \u3082\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08\u2192 [\xA725 \u30D0\u30C3\u30C1\u5909\u6570](#25-\u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB)\uFF09\u3002\r\n\r\n### \u578B\u4ED8\u304D\u6BD4\u8F03\uFF08v3.0.0\uFF09\r\n\r\n\u6BD4\u8F03\u65B9\u6CD5\u306F\u5024\u306E\u898B\u305F\u76EE\u3067\u306F\u306A\u304F\u3001\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u307E\u305F\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3078\u4F1D\u64AD\u3057\u305F\u5217\u578B\u3067\u6C7A\u307E\u308A\u307E\u3059\u3002\r\n\r\n- \u6587\u5B57\u5217\u578B\u3068\u578B\u4E0D\u660E\u5217\u306F Unicode \u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3067\u6BD4\u8F03\u3057\u307E\u3059\u3002`'20' > '100'` \u306F\u771F\u3067\u3059\r\n- NUMBER \u3068\u6570\u5024\u5F62\u5F0F CALC \u306F\u6700\u592730\u6841\u306E\u6709\u965010\u9032\u3092\u6587\u5B57\u5217\u306E\u307E\u307E\u53B3\u5BC6\u6BD4\u8F03\u3057\u307E\u3059\u3002\u7A7A\u30BB\u30EB\u3001\u7121\u9650\u5927\u3001\u691C\u8A3C\u5931\u6557\u5024\u3092\u542B\u3080\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u5217\u306B\u3082\u6C7A\u5B9A\u7684\u306A\u56FA\u5B9A\u9806\u304C\u3042\u308A\u307E\u3059\u3002\u7A7A\u767D\u306E\u307F\u306F\u6570\u50240\u3067\u306F\u306A\u304F\u300C\u305D\u306E\u4ED6\u975E\u6570\u5024\u300D\u3067\u3059\r\n- DATE / TIME / DATETIME \u306Fkintone\u306E\u6B63\u898F\u5316\u6E08\u307F\u8868\u73FE\u3092\u6587\u5B57\u5217\u3068\u3057\u3066\u6BD4\u8F03\u3057\u307E\u3059\r\n- DROP_DOWN / RADIO_BUTTON / STATUS\u7B49\u306F\u3001\u53D6\u5F97\u3067\u304D\u305F\u5B9A\u7FA9\u9806\u3092\u4F7F\u7528\u3057\u307E\u3059\r\n- \u6587\u5B57\u5217\uFF081\u884C\uFF09\u7B49\u3067kintone REST\u304C\u53D7\u7406\u3057\u306A\u3044`<` / `>`\u306F\u3001SELECT\u3067\u306F\u81EA\u52D5\u7684\u306B\u30ED\u30FC\u30AB\u30EB\u8A55\u4FA1\u3078\u5207\u308A\u66FF\u3048\u307E\u3059\u3002DML\u306F\u5BFE\u8C61\u96C6\u5408\u3092\u6697\u9ED9\u306B\u5E83\u3052\u305A\u3001\u5B9F\u884C\u524D\u306B\u30A8\u30E9\u30FC\u306B\u3057\u307E\u3059\r\n\r\nv2\u307E\u3067\u306F\u6570\u5B57\u3060\u3051\u306E\u6587\u5B57\u5217\u3092\u5024\u30D9\u30FC\u30B9\u3067\u6570\u5024\u6BD4\u8F03\u3059\u308B\u7D4C\u8DEF\u304C\u3042\u308A\u307E\u3057\u305F\u3002v3\u3067\u306F\u3053\u306E\u30DA\u30A2\u5358\u4F4D\u306E\u81EA\u52D5\u5207\u66FF\u3092\u5EC3\u6B62\u3057\u305F\u305F\u3081\u3001WHERE\u306E\u7D50\u679C\u884C\u3001\u96C6\u8A08\u5024\u3001DML\u5019\u88DC\u304C\u5909\u308F\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\u8A73\u7D30\u306F[v3.0.0 \u79FB\u884C\u30AC\u30A4\u30C9](ksql_v3_migration_guide.md)\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n### KLIKE / NOT KLIKE\uFF08kintone\u30AD\u30FC\u30EF\u30FC\u30C9\u691C\u7D22\uFF09\r\n\r\n`KLIKE` \u306FSQL `LIKE`\u3068\u306F\u5225\u306E\u6F14\u7B97\u5B50\u3067\u3059\u3002\u6761\u4EF6\u3092kintone\u306E `like` / `not like` \u3078\u5909\u63DB\u3057\u3001kintone\u5074\u3067\u30AD\u30FC\u30EF\u30FC\u30C9\u691C\u7D22\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT \u4EF6\u540D, \u62C5\u5F53\u8005\r\nFROM APP100\r\nWHERE \u4EF6\u540D KLIKE '\u81F3\u6025'\r\n\r\nSELECT \u4EF6\u540D\r\nFROM APP100\r\nWHERE \u4EF6\u540D NOT KLIKE '\u4FDD\u7559'\r\n```\r\n\r\n- `LIKE` \u306FkSQL\u306E\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\uFF0F\u90E8\u5206\u4E00\u81F4\u3092JavaScript\u3067\u8A55\u4FA1\u3057\u307E\u3059\u3002`KLIKE` \u306Fkintone\u306E\u30AD\u30FC\u30EF\u30FC\u30C9\u691C\u7D22\u3067\u3042\u308A\u3001\u534A\u89D2\u30FB\u5168\u89D2\u3001\u5927\u5C0F\u6587\u5B57\u3001\u5358\u8A9E\u5206\u5272\u306A\u3069\u306E\u4E00\u81F4\u898F\u5247\u306Fkintone\u306B\u6E96\u62E0\u3057\u307E\u3059\u3002**SQL\u306E\u90E8\u5206\u4E00\u81F4\u3068\u306F\u7570\u306A\u308B**\u70B9\u306B\u6CE8\u610F\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n - **\u4E00\u81F4\u6319\u52D5\u306F\u6587\u5B57\u7A2E\u30FB\u7528\u5B57\u7CFB\u306B\u3088\u3063\u3066\u7570\u306A\u308A\u307E\u3059**\uFF08\u8A73\u7D30\u306Fkintone\u306E\u691C\u7D22\u4ED5\u69D8\u306B\u6E96\u62E0\uFF09\u3002**\u4ECA\u56DE\u306E\u5B9F\u6A5F\u89B3\u6E2C**\u3067\u306F\u6B21\u306E\u3068\u304A\u308A\u3067\u3057\u305F\u3002**\u82F1\u6570\u5B57\u4F8B\u306F\u7A7A\u767D\u533A\u5207\u308A\u306E\u8A9E\uFF08\u30C8\u30FC\u30AF\u30F3\uFF09\u5358\u4F4D**\u3067\u4E00\u81F4\u3057\u8A9E\u306E\u4E00\u90E8\u3067\u306F\u4E00\u81F4\u305B\u305A\u3001**\u65E5\u672C\u8A9E\u4F8B\u306F2\u6587\u5B57\u4EE5\u4E0A\u306E\u90E8\u5206\u4E00\u81F4\uFF08\u4E2D\u9593\u3092\u542B\u3080\uFF09**\u3067\u4E00\u81F4\u30571\u6587\u5B57\u3067\u306F\u4E00\u81F4\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002\r\n\r\n | \u691C\u7D22 | \u5BFE\u8C61\u306E\u5024 | \u4E00\u81F4\uFF08\u89B3\u6E2C\u4F8B\uFF09 |\r\n |---|---|---|\r\n | `KLIKE 'TOKYO'` | `TOKYO TO` | \u25CB\uFF08\u7A7A\u767D\u533A\u5207\u308A\u306E\u8A9E `TOKYO`\uFF09 |\r\n | `KLIKE 'TOK'` / `'OKYO'` | `TOKYO TO` | \xD7\uFF08\u8A9E\u306E\u4E00\u90E8\u3067\u306F\u4E00\u81F4\u3057\u306A\u3044\uFF09 |\r\n | `KLIKE 'A'` | `A1` | \xD7\uFF08`A1` \u30671\u8A9E\uFF09 |\r\n | `KLIKE '\u4E38\u306E'` / `'\u306E\u5185'` | `\u4E38\u306E\u5185` | \u25CB\uFF082\u6587\u5B57\u4EE5\u4E0A\u306E\u90E8\u5206\u4E00\u81F4\u30FB\u4E2D\u9593\u3092\u542B\u3080\uFF09 |\r\n | `KLIKE '\u5185'` | `\u4E38\u306E\u5185` | \xD7\uFF081\u6587\u5B57\u3067\u306F\u4E00\u81F4\u3057\u306A\u3044\uFF09 |\r\n\r\n > \u4E0A\u8A18\u306F\u89B3\u6E2C\u3055\u308C\u305F\u4F8B\u3067\u3042\u308A\u3001kintone\u306E\u4E00\u81F4\u898F\u5247\u3092\u7DB2\u7F85\u7684\u306B\u5B9A\u7FA9\u3059\u308B\u3082\u306E\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u534A\u89D2\u30FB\u5168\u89D2\u3001\u5927\u5C0F\u6587\u5B57\u3001\u8A18\u53F7\u306E\u6271\u3044\u7B49\u306Fkintone\u306E\u4ED5\u69D8\u306B\u5F93\u3044\u307E\u3059\u3002\r\n - \u8FF7\u3063\u305F\u3089\u3001\u78BA\u5B9F\u306B\u90E8\u5206\u4E00\u81F4\u3055\u305B\u305F\u3044\u5834\u5408\u306F `LIKE`\uFF08JavaScript\u8A55\u4FA1\u30FBFULL_SCAN\uFF09\u3092\u3001kintone\u5074\u3067\u9AD8\u901F\u306B\u7D5E\u308A\u8FBC\u307F\u305F\u3044\u5834\u5408\u306F `KLIKE` \u3092\u4F7F\u3044\u5206\u3051\u3066\u304F\u3060\u3055\u3044\u3002\r\n- **\u6027\u80FD**: `LIKE` \u306FFULL_SCAN\u306B\u306A\u308A\u3001AND\u6761\u4EF6\u306B\u62BC\u3057\u4E0B\u3052\u53EF\u80FD\u306A\u5B89\u5168\u8FF0\u8A9E\uFF08`$id`\u30FB\u578B\u78BA\u8A8D\u6E08\u307FNUMBER\u306E `=` \u3068\u5B89\u5168\u6574\u6570\u3068\u306E\u53B3\u5BC6\u306A `<` / `>`\u30FB\u9078\u629E\u7CFB `IN` \u306A\u3069\uFF09\u304C\u306A\u3051\u308C\u3070\u5168\u4EF6\u53D6\u5F97\u306B\u306A\u308A\u307E\u3059\u3002\u5927\u898F\u6A21\u30A2\u30D7\u30EA\u3067\u306F\u53D6\u5F97\u4E0A\u9650\uFF08`maxRecords`\uFF09\u306B\u9054\u3057\u3066\u30A8\u30E9\u30FC\u306B\u306A\u308A\u304C\u3061\u3067\u3059\u3002`KLIKE` \u306FSIMPLE\u306E\u307E\u307Ekintone\u5074\u3067\u691C\u7D22\u3059\u308B\u305F\u3081\u3001\u5927\u898F\u6A21\u30A2\u30D7\u30EA\u3067\u3082\u9AD8\u901F\u3067\u3059\uFF08\u4F8B: \u6570\u5341\u4E07\u4EF6\u898F\u6A21\u306E\u30A2\u30D7\u30EA\u3067 `\u90FD\u9053\u5E9C\u770C LIKE '%\u6771\u4EAC%'` \u306F\u4E0A\u9650\u30A8\u30E9\u30FC\u3001`\u90FD\u9053\u5E9C\u770C KLIKE '\u6771\u4EAC\u90FD'` \u306F\u5373\u5FDC\uFF09\u3002\u305F\u3060\u3057\u4E0B\u8A18\u306E10\u4E07\u4EF6\u6253\u3061\u5207\u308A\u306B\u6CE8\u610F\u3002\r\n- SIMPLE SELECT\u3067\u306F\u5F93\u6765\u3069\u304A\u308AWHERE\u5168\u4F53\u3092kintone\u3078\u6E21\u3057\u307E\u3059\u3002FULL_SCAN SELECT\u3067\u3082\u3001KLIKE\u304CWHERE\u30EB\u30FC\u30C8\u304B\u3089AND\u3068\u62EC\u5F27\u3060\u3051\u3092\u7D4C\u7531\u3059\u308B\u5B89\u5168\u306A\u30EA\u30FC\u30D5\u306A\u3089\u3001kintone\u3078\u30D7\u30EC\u30D5\u30A3\u30EB\u30BF\u62BC\u3057\u4E0B\u3052\u3057\u3066\u6B8B\u308A\u306E\u6761\u4EF6\u3092JavaScript\u3067\u7CBE\u88FD\u3057\u307E\u3059\u3002\u3053\u308C\u306B\u3088\u308AKLIKE\u3068`LIKE`\u30FB\u95A2\u6570\u30FB\u96C6\u8A08\u30FB`DISTINCT`\u3092\u4F75\u7528\u3067\u304D\u307E\u3059\u3002\r\n ```sql\r\n -- \u4EF6\u540D\u306Fkintone\u3067\u7C97\u304F\u7D5E\u308A\u3001\u5099\u8003\u306FkSQL\u306E\u90E8\u5206\u4E00\u81F4\u3067\u7CBE\u88FD\r\n SELECT \u4EF6\u540D, \u5099\u8003 FROM APP100\r\n WHERE \u4EF6\u540D KLIKE '\u81F3\u6025' AND \u5099\u8003 LIKE '%\u7DCA\u6025%'\r\n ```\r\n- FULL_SCAN\u3067\u306E\u5236\u7D04: OR\u307E\u305F\u306F`NOT (...)`\u914D\u4E0B\u3001\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u3001CTE\uFF0F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u306EKLIKE\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002JOIN\u3068\u306E\u4F75\u7528\u306F\u3001\u3059\u3079\u3066\u306EJOIN\u304C`INNER JOIN`\u3067\u3001KLIKE\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u30C6\u30FC\u30D6\u30EB\u30A8\u30A4\u30EA\u30A2\u30B9\u3067\u660E\u793A\u3057\u305F\u5834\u5408\u3060\u3051\u8A31\u53EF\u3057\u307E\u3059\u3002`LEFT JOIN` / `RIGHT JOIN`\u3092\u542B\u3080SELECT\u3067\u306F\u3001\u5B89\u5168\u5074\u306BKLIKE\u3092\u62D2\u5426\u3057\u307E\u3059\u3002\u76F4\u63A5\u306E`NOT KLIKE`\u306FAND\u30EA\u30FC\u30D5\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n- \u53F3\u8FBA\u306F\u5358\u4E00\u5F15\u7528\u7B26\u306E\u6587\u5B57\u5217\u307E\u305F\u306F\u6587\u5B57\u5217\u30D0\u30C3\u30C1\u5909\u6570\u306B\u9650\u5B9A\u3055\u308C\u307E\u3059\u3002`%` \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002`_` \u306F\u4F7F\u7528\u3067\u304D\u307E\u3059\u304C\u30011\u6587\u5B57\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u3067\u306F\u306A\u304Fkintone\u691C\u7D22\u4E0A\u306E\u5358\u8A9E\u69CB\u6210\u6587\u5B57\u3067\u3059\u3002\r\n- DML \u3067\u306F\u6B21\u306E\u89AA\u30EC\u30B3\u30FC\u30C9 DML \u306E WHERE \u3067\u4F7F\u7528\u3067\u304D\u307E\u3059\uFF08v3.10.0\uFF09: **\u901A\u5E38\uFF08APPLY \u306A\u3057\uFF09\u306E\u89AA `UPDATE` / `DELETE`**\u3001\u304A\u3088\u3073 **APPLY \u8907\u6570\u89AA `UPDATE` \u306E\u89AA WHERE**\u3002\u524D\u8005\u306F WHERE \u5168\u4F53\u3092 kintone \u30AF\u30A8\u30EA\u3078 exact \u5909\u63DB\u3057\u3066\u5BFE\u8C61\u3092\u89E3\u6C7A\u3059\u308B\u305F\u3081 `OR` / `NOT` \u914D\u4E0B\u306E KLIKE \u3082\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\u5F8C\u8005\u306F\u5B89\u5168\u30D7\u30EC\u30D5\u30A3\u30EB\u30BF\uFF0B\u6B8B\u4F59\u8A55\u4FA1\u306E\u305F\u3081\u3001`OR` / `NOT` \u914D\u4E0B\u306A\u3069 native query \u306B\u5B8C\u5168\u9069\u7528\u3067\u304D\u306A\u3044 KLIKE \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002**\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB `UPDATE` / `DELETE`\u30FB`REORDER`\u30FB`INSERT` / `INSERT ... SELECT`\u30FB`UPSERT` / `UPSERT ... SELECT`\u30FB\u72EC\u7ACB\u3057\u305F `VALIDATE` \u3067\u306F\u5F15\u304D\u7D9A\u304D\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093**\uFF08JS \u8A55\u4FA1\u7D4C\u8DEF\u306E\u305F\u3081\uFF09\u3002SQL `LIKE` / `NOT LIKE` \u306F\u901A\u5E38 DML \u3067\u306F\u5F15\u304D\u7D9A\u304D\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF08JS \u8A55\u4FA1\u304C\u5FC5\u8981\uFF09\u3002\r\n- \u5229\u7528\u53EF\u80FD\u306A\u30D5\u30A3\u30FC\u30EB\u30C9\u306F[kintone\u516C\u5F0F\u306E\u6F14\u7B97\u5B50\u5BFE\u5FDC\u8868](https://cybozu.dev/ja/kintone/docs/overview/query/)\u306B\u5F93\u3044\u307E\u3059\u3002\u6587\u5B57\u52171\u884C\u30FB\u8907\u6570\u884C\u3001\u30EA\u30C3\u30C1\u30A8\u30C7\u30A3\u30BF\u30FC\u3001\u30EA\u30F3\u30AF\u3001\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\u306A\u3069\u304C\u5BFE\u8C61\u3067\u3059\u3002\u975E\u5BFE\u5FDC\u30D5\u30A3\u30FC\u30EB\u30C9\u306Fkintone API\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002\r\n- kintone\u306F\u30AD\u30FC\u30EF\u30FC\u30C9\u4E00\u81F4\u304C10\u4E07\u4EF6\u306B\u9054\u3059\u308B\u3068\u691C\u7D22\u3092\u6253\u3061\u5207\u308A\u307E\u3059\u3002**CLI / MCP / \u30D7\u30E9\u30B0\u30A4\u30F3\u3059\u3079\u3066\u3067\u6253\u3061\u5207\u308A\u3092\u691C\u51FA\u3057\u307E\u3059**\uFF08\u30D7\u30E9\u30B0\u30A4\u30F3\u306F v3.10.0 \u3067 raw fetch \u306B\u3088\u308A\u30EC\u30B9\u30DD\u30F3\u30B9\u30D8\u30C3\u30C0\u30FC `X-Cybozu-Warning` \u3092\u8AAD\u307F\u53D6\u308A\u307E\u3059\uFF09\u3002SELECT \u3067\u306F\u7D50\u679C\u6B20\u843D\u306E\u53EF\u80FD\u6027\u3092\u8B66\u544A\u3057\u307E\u3059\u3002\u8AAD\u307F\u53D6\u308A\u7D50\u679C\u3092\u66F8\u304D\u8FBC\u307F\u3084\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u5B9F\u4F53\u5316\u306B\u4F7F\u3046\u5834\u5408\u3001\u304A\u3088\u3073 KLIKE \u3092\u542B\u3080\u89AA DML \u306E\u5BFE\u8C61\u89E3\u6C7A\u3067\u306F\u3001\u4E0D\u5B8C\u5168\u306A\u5BFE\u8C61\u96C6\u5408\u3067\u5B9F\u884C\u3057\u306A\u3044\u3088\u3046 `SearchAbortedError` \u3067\u30A8\u30E9\u30FC\u7D42\u4E86\u3057\u3001\u66F8\u304D\u8FBC\u307F0\u4EF6\u3067 fail-closed \u3068\u3057\u307E\u3059\u3002\r\n- `KLIKE` \u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u53C2\u7167\u3059\u308B\u3068\u304D\u306F `` `KLIKE` `` \u3068\u8A18\u8FF0\u3057\u307E\u3059\u3002\r\n\r\n### IN / NOT IN\uFF08\u5024\u30EA\u30B9\u30C8\u306B\u3088\u308B\u4E00\u81F4\u30FB\u9664\u5916\uFF09\r\n\r\n`IN` \u306F\u5217\u6319\u3057\u305F\u5024\u306E**\u3044\u305A\u308C\u304B\u306B\u4E00\u81F4**\u3059\u308B\u884C\u3001`NOT IN` \u306F**\u3044\u305A\u308C\u306B\u3082\u4E00\u81F4\u3057\u306A\u3044**\u884C\u3092\u9078\u3073\u307E\u3059\u3002\r\n\r\n```sql\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u9032\u884C\u4E2D', '\u5B8C\u4E86', '\u30EC\u30D3\u30E5\u30FC\u4E2D')\r\nWHERE \u533A\u5206 IN (1, 2, 3)\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 NOT IN ('\u30AD\u30E3\u30F3\u30BB\u30EB', '\u5374\u4E0B')\r\n```\r\n\r\n**IN \u30EA\u30B9\u30C8\u306E\u5024\uFF08\u69CB\u6587\uFF09**\r\n\r\n- \u5358\u4E00\u5F15\u7528\u7B26\u306E\u6587\u5B57\u5217 `'...'`\u30FB\u6570\u5024\u30FB\u30D0\u30C3\u30C1\u5909\u6570 `@\u540D\u524D` \u3092\u6307\u5B9A\u3067\u304D\u3001**1 \u8981\u7D20\u4EE5\u4E0A\u304C\u5FC5\u9808**\u3067\u3059\u3002\u6587\u5B57\u5217\u306F\u30C0\u30D6\u30EB\u30AF\u30A9\u30FC\u30C8\u3067\u306A\u304F\u5358\u4E00\u5F15\u7528\u7B26\u3067\u3059\uFF08`IN (\"A\")` \u306F\u69CB\u6587\u30A8\u30E9\u30FC\uFF09\u3002\r\n- \u8CA0\u6570\u30EA\u30C6\u30E9\u30EB\u3082\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08`IN (-1, -2)`\uFF09\u3002\r\n- **`IN ()`\uFF080 \u8981\u7D20\uFF09\u306F\u66F8\u3051\u307E\u305B\u3093**\uFF08ParseError\uFF09\u3002\u300C\u7A7A\uFF0F\u672A\u9078\u629E\u300D\u3092\u63A2\u3059\u306E\u306F `IN ('')` \u3067\u3059\uFF08\u5F8C\u8FF0\uFF09\u3002\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u6E21\u3059 `IN (SELECT ...)` \u306F\u5225\u9805\u3067\u3059\uFF08\u5F8C\u8FF0\uFF09\u3002\r\n\r\n**\u4E00\u81F4\u306E\u610F\u5473\u8AD6\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u3067\u7570\u306A\u308A\u307E\u3059**\r\n\r\n- **\u5358\u4E00\u5024\u30D5\u30A3\u30FC\u30EB\u30C9**\uFF08\u30C6\u30AD\u30B9\u30C8\u30FB\u6570\u5024\u30FB\u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3\u30FB\u30E9\u30B8\u30AA\u30FB\u65E5\u4ED8\u30FB\u30B9\u30C6\u30FC\u30BF\u30B9\u7B49\uFF09\uFF1D**\u30B9\u30AB\u30E9\u30FC\u7B49\u5024**\uFF08`\u5217 = \u50241 OR \u5217 = \u50242 \u2026`\uFF09\u3002**\u6A19\u6E96SQL\u3068\u540C\u3058**\u3067\u3059\u3002\r\n- **\u8907\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9**\uFF08\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u30FB\u8907\u6570\u9078\u629E\uFF09\uFF1D**\u9078\u629E\u96C6\u5408\u304C\u5217\u6319\u5024\u306E\u5C11\u306A\u304F\u3068\u3082 1 \u3064\u3092\u542B\u3080**\uFF08\u96C6\u5408\u306E overlap\uFF09\u3002\u6A19\u6E96SQL \u306E\u30B9\u30AB\u30E9\u30FC `IN` \u3068\u306F\u7570\u306A\u308A\u307E\u3059\uFF08\u5F8C\u8FF0\u306E\u300C\u6A19\u6E96SQL\u3068\u306E\u9055\u3044\u300D\uFF09\u3002\r\n- \u30E6\u30FC\u30B6\u30FC\u30FB\u7D44\u7E54\u30FB\u30B0\u30EB\u30FC\u30D7\u9078\u629E\u30FB\u4F5C\u696D\u8005\u3082\u8907\u6570\u5024\u306A\u306E\u3067\u3001`code` \u306E\u96C6\u5408 overlap\uFF08\u3044\u305A\u308C\u304B\u3092\u542B\u3080\uFF09\u3067\u5224\u5B9A\u3057\u307E\u3059\u3002\u4F5C\u6210\u8005\u30FB\u66F4\u65B0\u8005\u306F\u5358\u4E00\u5024\u3067 `code` \u306E\u30B9\u30AB\u30E9\u30FC\u7B49\u5024\u3067\u3059\uFF08\u3044\u305A\u308C\u3082\u8868\u793A\u540D\u3067\u306F\u306A\u304F `code` \u3067\u6BD4\u8F03\uFF09\u3002\r\n- \u578B\u60C5\u5831\u3092\u53D6\u5F97\u3067\u304D\u306A\u3044\u5024\u3001\u578B\u3068\u5024\u306E\u5F62\u304C\u4E00\u81F4\u3057\u306A\u3044\u5834\u5408\u306F\u6587\u5B57\u5217\u6BD4\u8F03\u3092\u7DAD\u6301\u3057\u307E\u3059\u3002\r\n- \u9078\u629E\u7CFB\u306E\u7A7A\uFF0F\u672A\u8A2D\u5B9A\u30BB\u30EB\u306F `IN ('')` \u306B\u4E00\u81F4\u3057\u3001`NOT IN ('')` \u3067\u9664\u5916\u3055\u308C\u307E\u3059\uFF08\u7A7A\u30B9\u30AB\u30E9\u30FC\u5024\u306E\u6295\u5F71\u3082\u7A7A\u6587\u5B57\u3067\u8FD4\u3057\u307E\u3059\uFF09\u3002\r\n\r\n\u3053\u306E\u898F\u5247\u306F\u30EA\u30C6\u30E9\u30EB\uFF0F\u30D0\u30C3\u30C1\u5909\u6570\u306E IN \u30EA\u30B9\u30C8\u30FB`IN (SELECT ...)`\u30FB\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306E JavaScript \u8A55\u4FA1\u3059\u3079\u3066\u306B\u9069\u7528\u3055\u308C\u307E\u3059\u3002**\u5B9F\u5728\u3059\u308B\u5024\u306B\u5BFE\u3059\u308B\u4E00\u81F4\u7D50\u679C\u306F\u3001REST \u62BC\u3057\u4E0B\u3052\u3067\u3082 JS \u8A55\u4FA1\u3067\u3082\u540C\u3058**\u3067\u3059\uFF08\u5B9A\u7FA9\u5916\u306E\u9078\u629E\u80A2\u5024\u3060\u3051\u306F\u3001\u62BC\u3057\u4E0B\u3052\u7D4C\u8DEF\u3067\u5B9F\u884C\u30A8\u30E9\u30FC\u306B\u306A\u308A\u5F97\u307E\u3059\u30FB\u4E0B\u8A18\uFF09\u3002\r\n\r\n```sql\r\n-- \u7A7A\uFF0F\u672A\u8A2D\u5B9A\u306E\u9078\u629E\u30BB\u30EB\u3092\u62BD\u51FA\uFF08\u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3\u306F = '' \u304C\u4F7F\u3048\u306A\u3044\u305F\u3081 IN ('') \u3092\u4F7F\u3046\uFF09\r\nWHERE \u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3 IN ('') -- \u672A\u9078\u629E\u306E\u30EC\u30B3\u30FC\u30C9\r\nWHERE \u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3 NOT IN ('') -- \u9078\u629E\u6E08\u307F\u306E\u30EC\u30B3\u30FC\u30C9\r\nWHERE \u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3 IN ('', '\u5BFE\u5FDC\u4E2D') -- \u672A\u9078\u629E \u307E\u305F\u306F\u300C\u5BFE\u5FDC\u4E2D\u300D\r\n```\r\n\r\n> **\u6A19\u6E96SQL\u3068\u306E\u9055\u3044\uFF08\u8907\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9\u306E `IN`\uFF09** \r\n> \u6A19\u6E96SQL\u306E `x IN ('A','B')` \u306F `x = 'A' OR x = 'B'` \u3068\u3044\u3046\u30B9\u30AB\u30E9\u30FC\u7B49\u5024\u3067\u3001**`x` \u3092 1 \u3064\u306E\u5024**\u3068\u3057\u3066 `'A'`\u30FB`'B'` \u3068\u7A81\u304D\u5408\u308F\u305B\u307E\u3059\uFF08\u8981\u7D20\u3054\u3068\u306B\u306F\u7167\u5408\u3057\u307E\u305B\u3093\uFF09\u3002\u6A19\u6E96SQL\u306F 1 \u30D5\u30A3\u30FC\u30EB\u30C9\uFF1D\u30B9\u30AB\u30E9\u30FC\u304C\u524D\u63D0\u3067\u591A\u5024\u5217\u3092\u6301\u305F\u305A\u3001\u591A\u5024\u306F\u5225\u884C\u306B\u6B63\u898F\u5316\u3057\u3066 `EXISTS` \u306A\u3069\u3067\u8868\u3059\u305F\u3081\u3067\u3059\u3002 \r\n> \u4E00\u65B9 kintone \u306E\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u30FB\u8907\u6570\u9078\u629E\u306F 1 \u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u8907\u6570\u5024\u306A\u306E\u3067\u3001kSQL \u306F kintone \u30CD\u30A4\u30C6\u30A3\u30D6\u306E `in` \u306B\u5408\u308F\u305B\u3001**\u96C6\u5408\u3092\u8981\u7D20\u306B\u958B\u3044\u3066\u300C\u5217\u6319\u5024\u306E\u5C11\u306A\u304F\u3068\u3082 1 \u3064\u3092\u542B\u3080\u304B\u300D**\uFF08\u96C6\u5408\u306E overlap\uFF09\u3067\u5224\u5B9A\u3057\u307E\u3059\u3002\u3053\u308C\u306B\u3088\u308A `['A']` \u3082 `['A','B']` \u3082 `IN ('A','B')` \u306B**\u4E00\u81F4\u3057\u307E\u3059**\u3002\u6A19\u6E96SQL\u3067\u540C\u7FA9\u3092\u66F8\u304F\u306A\u3089\u4E2D\u9593\u30C6\u30FC\u30D6\u30EB\u306E `EXISTS`\uFF08\u30BB\u30DF\u7D50\u5408\uFF09\u3084\u914D\u5217 overlap\uFF08`checkbox && ARRAY[...]`\uFF09\u306B\u76F8\u5F53\u3057\u307E\u3059\u3002\u5B9F\u5728\u3059\u308B\u5024\u306B\u5BFE\u3059\u308B\u4E00\u81F4\u7D50\u679C\u306F REST \u62BC\u3057\u4E0B\u3052\u3067\u3082 JS \u8A55\u4FA1\u3067\u3082\u540C\u3058\u3067\u3059\uFF08\u5358\u4E00\u9078\u629E\u30FB\u30C6\u30AD\u30B9\u30C8\u30FB\u6570\u5024\u306F\u5F93\u6765\u3069\u304A\u308A\u30B9\u30AB\u30E9\u30FC\u7B49\u5024\u3067\u3001\u6A19\u6E96SQL\u3068\u540C\u3058\uFF09\u3002\r\n\r\n`\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9`\uFF08\u9078\u629E\u80A2 A/B/C\uFF09\u306B\u5BFE\u3059\u308B\u5224\u5B9A\u4F8B:\r\n\r\n| \u30D5\u30A3\u30FC\u30EB\u30C9\u5024 | `IN ('A','B')` | `IN ('')` | `NOT IN ('')` |\r\n|---|:---:|:---:|:---:|\r\n| `[]`\uFF08\u672A\u9078\u629E\uFF09 | \u2717 | \u2713 | \u2717 |\r\n| `['A']` | \u2713 | \u2717 | \u2713 |\r\n| `['C']` | \u2717 | \u2717 | \u2713 |\r\n| `['A','C']` | \u2713 | \u2717 | \u2713 |\r\n| `['A','B','C']` | \u2713 | \u2717 | \u2713 |\r\n\r\n- **`IN ('\u5217\u6319\u5024', ...)`**\uFF1A\u5217\u6319\u5024\u306E\u3044\u305A\u308C\u304B\u3092**\u542B\u3080**\u884C\u306B\u4E00\u81F4\u3057\u307E\u3059\u3002`['A','C']` \u306F\u30EA\u30B9\u30C8\u5916\u306E `C` \u3092\u542B\u3093\u3067\u3044\u3066\u3082 `A` \u304C\u3042\u308C\u3070\u4E00\u81F4\u3067\u3001\u90E8\u5206\u96C6\u5408\u3084\u5B8C\u5168\u4E00\u81F4\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\r\n- **`IN ('')`\uFF08\u7A7A\u6587\u5B57 1 \u8981\u7D20\uFF09\uFF1D\u672A\u9078\u629E\uFF08\u7A7A\uFF09\u306E\u884C\u3060\u3051\u306B\u4E00\u81F4**\u3057\u307E\u3059\u3002`= ''` \u304C\u4F7F\u3048\u306A\u3044\u9078\u629E\u7CFB\uFF08\u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3\u7B49\uFF09\u306E\u300C\u7A7A\u300D\u5224\u5B9A\u306B\u3082\u4F7F\u3044\u307E\u3059\u3002\u7A7A\u6587\u5B57\u3092\u542B\u3081\u308B `IN ('', 'A')` \u306F\u300C\u672A\u9078\u629E \u307E\u305F\u306F A \u3092\u542B\u3080\u300D\u3067\u3059\u3002\r\n- **`NOT IN ('')`\uFF1D\u9078\u629E\u304C 1 \u3064\u4EE5\u4E0A\u3042\u308B\u884C**\uFF08`[]` \u4EE5\u5916\uFF09\u306B\u4E00\u81F4\uFF1D`IN ('')` \u306E\u88DC\u96C6\u5408\u3067\u3059\u3002\r\n- **`NOT IN ('A','B')`\uFF1DA \u3082 B \u3082\u542B\u307E\u306A\u3044\u884C**\u306B\u4E00\u81F4\u3057\u307E\u3059\uFF08\u4E0A\u8868\u306A\u3089 `[]` \u3068 `['C']`\uFF09\u3002\r\n\r\nFULL_SCAN \u306E `WHERE` \u3067\u306F\u3001\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u3068\u9078\u629E\u80A2\u306E\u5B9F\u5728\u3092\u78BA\u8A8D\u3067\u304D\u305F\r\n`DROP_DOWN`\uFF0F`RADIO_BUTTON`\uFF0F`CHECK_BOX`\uFF0F`MULTI_SELECT` \u306E `IN`\uFF0F`NOT IN`\r\n\uFF08\u7A7A\u3067\u306A\u3044\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u306E\u307F\uFF09\u3092 kintone \u306E\u4E8B\u524D\u7D5E\u308A\u8FBC\u307F\u306B\u3082\u4F7F\u7528\u3057\u307E\u3059\u3002\u7D50\u679C\u306F\u53D6\u5F97\u5F8C\u306B\u540C\u3058\u578B\u4ED8\u304D\u898F\u5247\u3067\u518D\u8A55\u4FA1\u3057\u307E\u3059\u3002\r\n\u5B58\u5728\u3057\u306A\u3044\u9078\u629E\u80A2\u3001\u7A7A\u6587\u5B57\u3001\u578B\u60C5\u5831\u30FB\u9078\u629E\u80A2\u60C5\u5831\u3092\u53D6\u5F97\u3067\u304D\u306A\u3044\u5834\u5408\u306F\u62BC\u3057\u4E0B\u3052\u305A\u3001JavaScript \u8A55\u4FA1\u3060\u3051\u3092\u884C\u3044\u307E\u3059\u3002\r\n\u30E6\u30FC\u30B6\u30FC\u30FB\u7D44\u7E54\u30FB\u30B0\u30EB\u30FC\u30D7\u9078\u629E\u306F\u3053\u306E\u6700\u9069\u5316\u306E\u5BFE\u8C61\u5916\u3067\u3059\u3002\u30D7\u30ED\u30BB\u30B9\u7BA1\u7406\u304C\u6709\u52B9\u3067\u3001\u5B9F\u884C\u30E6\u30FC\u30B6\u30FC\u306E\u8868\u793A\u8A00\u8A9E\u306B\u304A\u3051\u308B\u72B6\u614B\u540D\u306E\u5B9F\u5728\u3092\u78BA\u8A8D\u3067\u304D\u305F\u30B9\u30C6\u30FC\u30BF\u30B9\u306E `IN`\uFF0F`NOT IN` \u3082\u4E8B\u524D\u7D5E\u308A\u8FBC\u307F\u306B\u4F7F\u7528\u3057\u307E\u3059\u3002\u30D7\u30ED\u30BB\u30B9\u7BA1\u7406\u304C\u7121\u52B9\u3001\u72B6\u614B\u540D\u304C\u975E\u5B9F\u5728\u3001\u307E\u305F\u306F\u7A7A\u6587\u5B57\u306E\u5834\u5408\u306F\u62BC\u3057\u4E0B\u3052\u307E\u305B\u3093\u3002\r\n\r\n> **\u9078\u629E\u7CFB\u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u300C\u5B9A\u7FA9\u306B\u7121\u3044\u9078\u629E\u80A2\u5024\u300D\u3092\u6E21\u3057\u305F\u3068\u304D\u306E\u6CE8\u610F\uFF08\u91CD\u8981\uFF09** \r\n> `DROP_DOWN`\uFF0F`RADIO_BUTTON`\uFF0F`CHECK_BOX`\uFF0F`MULTI_SELECT`\uFF0F\u30B9\u30C6\u30FC\u30BF\u30B9\u306B\u3001\u305D\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u9078\u629E\u80A2\u3068\u3057\u3066**\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u306A\u3044\u5024**\u3092 `IN`\uFF0F`NOT IN` \u3078\u6E21\u3059\u3068\u3001\u305D\u306E `IN` \u304C **kintone REST \u3078\u62BC\u3057\u4E0B\u3052\u3089\u308C\u308B\u304B\u5426\u304B**\u3067\u6319\u52D5\u304C\u5206\u304B\u308C\u307E\u3059\uFF08\u5B9F\u884C\u30E2\u30FC\u30C9\u304C SIMPLE \u304B FULL_SCAN \u304B\u3067\u306F\u3042\u308A\u307E\u305B\u3093\uFF09\u3002\r\n> - **`WHERE` \u5168\u4F53\u304C REST \u306B\u5B8C\u5168\u62BC\u3057\u4E0B\u3052\u3055\u308C\u308B\u5834\u5408**\uFF08\u7D14\u7C8B\u306A SIMPLE \u306E\u307B\u304B\u3001`DISTINCT`\uFF0F`GROUP BY`\uFF0F`ORDER BY` \u306A\u3069\u3067\u5B9F\u884C\u30E2\u30FC\u30C9\u304C FULL_SCAN \u306B\u306A\u3063\u3066\u3082\u3001`WHERE` \u81EA\u4F53\u306F\u62BC\u3057\u4E0B\u3052\u53EF\u80FD\u306A\u3068\u304D\uFF09: \u5B9A\u7FA9\u5916\u5024\u304C kintone \u306B\u6E21\u308A\u3001`GAIA_IQ10`\uFF08\u9805\u76EE\u306B\u300C\u5024\u300D\u306F\u5B58\u5728\u3057\u307E\u305B\u3093\uFF09\u3067**\u5B9F\u884C\u30A8\u30E9\u30FC**\u306B\u306A\u308A\u307E\u3059\u3002\r\n> - **`WHERE` \u306B JavaScript \u8A55\u4FA1\u304C\u5FC5\u9808\u306A\u90E8\u5206\u304C\u3042\u308B\u5834\u5408**\uFF08\u95A2\u6570\u30FB\u7B97\u8853\u5F0F\u30FB`LIKE`\u30FB`IN (SELECT ...)` \u306A\u3069\u306E\u6B8B\u4F59\u304C\u3042\u308A\u3001\u5B89\u5168\u30EA\u30FC\u30D5\u3060\u3051\u3092\u4E8B\u524D\u7D5E\u308A\u8FBC\u307F\u3059\u308B\u7D4C\u8DEF\uFF09\u3084\u3001**`CASE WHEN` \u306A\u3069\u306E\u6761\u4EF6**\uFF08\u2192 \xA74\uFF09: \u5B9A\u7FA9\u5916\u5024\u30FB\u7A7A\u6587\u5B57\u3092\u542B\u3080\u9078\u629E\u7CFB `IN` \u306F\u62BC\u3057\u4E0B\u3052\u305A JS \u3067\u8A55\u4FA1\u3059\u308B\u305F\u3081\u3001**\u30A8\u30E9\u30FC\u306B\u306A\u3089\u305A\u5358\u306B\u4E00\u81F4 0 \u4EF6**\uFF08`NOT IN` \u306F\u5168\u4E00\u81F4\uFF09\u306B\u306A\u308A\u307E\u3059\u3002\r\n>\r\n> \u30C6\u30AD\u30B9\u30C8\u30FB\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u5B9A\u7FA9\u9078\u629E\u80A2\u306E\u6982\u5FF5\u304C\u7121\u3044\u305F\u3081\u3001\u672A\u4E00\u81F4\u3067\u3082\u5E38\u306B 0 \u4EF6\uFF08\u30A8\u30E9\u30FC\u306A\u3057\uFF09\u3067\u3059\u3002**\u30D0\u30C3\u30C1\u5909\u6570**\u306F\u7F6E\u63DB\u5F8C\u306B\u901A\u5E38\u306E `IN` \u30EA\u30B9\u30C8\u306B\u306A\u308B\u305F\u3081\u3001\u4E0A\u306E\u300C\u5B8C\u5168\u62BC\u3057\u4E0B\u3052\u300D\u7D4C\u8DEF\u3067\u306F\u5B9A\u7FA9\u5916\u5024\u304C\u6DF7\u3058\u308B\u3068 `GAIA_IQ10` \u306B\u306A\u308A\u5F97\u307E\u3059\uFF08\u4E8B\u524D\u306B\u6709\u52B9\u5024\u3078\u7D5E\u3063\u3066\u304F\u3060\u3055\u3044\uFF09\u3002\u4E00\u65B9 **`IN (SELECT ...)` \u306F\u5E38\u306B JavaScript \u8A55\u4FA1**\uFF08REST \u3078\u6E21\u3055\u306A\u3044\uFF09\u306A\u306E\u3067\u3001\u3053\u306E\u7D4C\u8DEF\u3067\u306F `GAIA_IQ10` \u306B\u306F\u306A\u308A\u307E\u305B\u3093\u3002\r\n\r\n### IN (SELECT ...) / NOT IN (SELECT ...)\uFF08\u30B5\u30D6\u30AF\u30A8\u30EA\uFF09\r\n\r\n\u5225\u30A2\u30D7\u30EA\u306E\u691C\u7D22\u7D50\u679C\u3092 IN \u30EA\u30B9\u30C8\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\n-- APP88 \u304B\u3089\u300C\u30E9\u30F3\u30AF A\u300D\u306E\u9867\u5BA2\u540D\u4E00\u89A7\u3092\u53D6\u5F97\u3057\u3066\u30D5\u30A3\u30EB\u30BF\r\nSELECT * FROM APP88\r\nWHERE \u9867\u5BA2\u540D IN (SELECT \u9867\u5BA2\u540D FROM APP89 WHERE \u9867\u5BA2\u30E9\u30F3\u30AF = 'A')\r\n\r\n-- \u9664\u5916\r\nSELECT * FROM APP88\r\nWHERE \u9867\u5BA2\u540D NOT IN (SELECT \u9867\u5BA2\u540D FROM APP89 WHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u505C\u6B62')\r\n```\r\n\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u306F SELECT 1\u5217\u76EE\uFF08\u307E\u305F\u306F `SELECT \u30D5\u30A3\u30FC\u30EB\u30C9\u540D`\uFF09\u306E\u5024\u30BB\u30C3\u30C8\u3092\u8FD4\u3057\u307E\u3059\r\n- \u81EA\u52D5\u7684\u306B FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u81EA\u4F53\u3082 SIMPLE / FULL_SCAN \u3092\u81EA\u52D5\u5224\u5B9A\u3057\u307E\u3059\r\n\r\n### EXISTS / NOT EXISTS\uFF08\u30B5\u30D6\u30AF\u30A8\u30EA\uFF09\r\n\r\n\u30B5\u30D6\u30AF\u30A8\u30EA\u304C 1 \u4EF6\u4EE5\u4E0A\u8FD4\u3059\u304B\u3069\u3046\u304B\u3067\u6761\u4EF6\u3092\u5224\u5B9A\u3057\u307E\u3059\uFF08\u975E\u76F8\u95A2\u306E\u307F\uFF09\u3002\r\n\r\n```sql\r\n-- \u30B5\u30D6\u30AF\u30A8\u30EA\u304C 1\u4EF6\u4EE5\u4E0A\u3042\u308C\u3070\u5168\u884C\u3092\u8FD4\u3059\r\nSELECT * FROM APP88\r\nWHERE EXISTS (SELECT $id FROM APP89 WHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u627F\u8A8D\u6E08\u307F')\r\n\r\n-- \u30B5\u30D6\u30AF\u30A8\u30EA\u304C 0\u4EF6\u306A\u3089\u5168\u884C\u3092\u8FD4\u3059\r\nSELECT * FROM APP88\r\nWHERE NOT EXISTS (SELECT $id FROM APP89 WHERE \u30D5\u30E9\u30B0 = 'NG')\r\n\r\n-- AND / OR \u3068\u7D44\u307F\u5408\u308F\u305B\r\nSELECT \u9867\u5BA2\u540D, \u91D1\u984D FROM APP88\r\nWHERE \u91D1\u984D > 10000\r\n AND EXISTS (SELECT $id FROM APP89 WHERE \u627F\u8A8D\u30D5\u30E9\u30B0 = '1')\r\n```\r\n\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u306F 1 \u56DE\u3060\u3051\u5B9F\u884C\u3055\u308C\u3001\u5168\u884C\u306B\u540C\u3058\u7D50\u679C\uFF08\u771F/\u507D\uFF09\u304C\u9069\u7528\u3055\u308C\u307E\u3059\r\n- **\u76F8\u95A2\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u975E\u5BFE\u5FDC**\uFF08\u5916\u5074\u30C6\u30FC\u30D6\u30EB\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u53C2\u7167\u4E0D\u53EF\uFF09\r\n- \u81EA\u52D5\u7684\u306B FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\r\n\r\n### \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\uFF08WHERE \u53F3\u8FBA\uFF09\r\n\r\n\u6BD4\u8F03\u6F14\u7B97\u5B50\u306E\u53F3\u8FBA\u306B 1 \u884C 1 \u5217\u3092\u8FD4\u3059\u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u5168\u4F53\u306E\u5E73\u5747\u3068\u6BD4\u8F03\r\nSELECT * FROM APP100\r\nWHERE \u91D1\u984D > (SELECT AVG(\u91D1\u984D) FROM APP100)\r\n\r\n-- \u5225\u30A2\u30D7\u30EA\u306E\u6700\u5927\u5024\u3068\u6BD4\u8F03\r\nSELECT * FROM APP100\r\nWHERE \u91D1\u984D >= (SELECT MAX(\u4E0A\u9650\u91D1\u984D) FROM APP200 WHERE \u533A\u5206 = '\u6A19\u6E96')\r\n```\r\n\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u306F 1 \u884C 1 \u5217\u3092\u8FD4\u3059\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF080 \u884C\u307E\u305F\u306F 2 \u884C\u4EE5\u4E0A\u306F\u30A8\u30E9\u30FC\uFF09\r\n- GROUP BY \u306A\u3057\u306E\u96C6\u8A08\u30B5\u30D6\u30AF\u30A8\u30EA\uFF08`AVG(...)` \u7B49\uFF09\u306F\u5BFE\u8C61 0 \u4EF6\u3067\u3082 1 \u884C\uFF08\u5024 `0`\uFF09\u3092\u8FD4\u3059\u305F\u3081\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u305B\u3093\uFF08\xA78\u300C0 \u4EF6\u6642\u306E\u6319\u52D5\u300D\uFF09\r\n- **\u76F8\u95A2\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u975E\u5BFE\u5FDC**\uFF08\u5916\u5074\u30C6\u30FC\u30D6\u30EB\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u53C2\u7167\u4E0D\u53EF\uFF09\r\n- \u81EA\u52D5\u7684\u306B FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\r\n\r\n### BETWEEN\uFF08\u7BC4\u56F2\u6307\u5B9A\uFF09\r\n\r\n`BETWEEN a AND b` \u306F `>= a AND <= b` \u3068\u540C\u7B49\u3067\u3059\u3002\r\n\r\n```sql\r\nWHERE \u91D1\u984D BETWEEN 10000 AND 50000\r\nWHERE \u4F5C\u6210\u65E5\u6642 BETWEEN '2024-01-01' AND '2024-12-31'\r\n```\r\n\r\n### LIKE / NOT LIKE\uFF08\u90E8\u5206\u4E00\u81F4\u30FB\u9664\u5916\uFF09\r\n\r\n| \u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9 | \u610F\u5473 |\r\n|----------------|------|\r\n| `%` | 0\u6587\u5B57\u4EE5\u4E0A\u306E\u4EFB\u610F\u306E\u6587\u5B57\u5217 |\r\n| `_` | \u4EFB\u610F\u306E1\u6587\u5B57 |\r\n\r\n```sql\r\nWHERE \u6C0F\u540D LIKE '\u7530%' -- \u300C\u7530\u300D\u3067\u59CB\u307E\u308B\r\nWHERE \u30E1\u30E2 LIKE '%\u91CD\u8981%' -- \u300C\u91CD\u8981\u300D\u3092\u542B\u3080\r\nWHERE \u30B3\u30FC\u30C9 LIKE 'A__' -- \u300CA\u300D+\u4EFB\u610F2\u6587\u5B57\r\nWHERE \u6C0F\u540D NOT LIKE '\u7530%' -- \u300C\u7530\u300D\u3067\u59CB\u307E\u3089\u306A\u3044\r\nWHERE \u9867\u5BA2\u540D LIKE '\u4F1A\u793E' -- \u300C\u4F1A\u793E\u300D\u3092\u542B\u3080\uFF08\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u306A\u3057\uFF1D\u90E8\u5206\u4E00\u81F4\uFF09\r\n```\r\n\r\n> **\u8A55\u4FA1\u7D4C\u8DEF\uFF08Breaking\uFF09**
\r\n> `LIKE` / `NOT LIKE`\u306F\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u306E\u6709\u7121\u306B\u304B\u304B\u308F\u3089\u305Akintone\u3078\u6E21\u3055\u305A\u3001\u5168\u4EF6\u53D6\u5F97\u5F8C\u306BJavaScript\u3067\u8A55\u4FA1\u3057\u307E\u3059\u3002`%` / `_`\u4ED8\u304D\u306F\u4E0A\u8868\u306ESQL\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u3001\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u306A\u3057\u306E`LIKE '\u4F1A\u793E'`\u306FkSQL\u72EC\u81EA\u4ED5\u69D8\u306E\u90E8\u5206\u4E00\u81F4\uFF08`includes`\uFF09\u3067\u3059\u3002kintone\u306E\u5358\u8A9E\uFF08\u30C8\u30FC\u30AF\u30F3\uFF09\u691C\u7D22\u306B\u306F\u59D4\u8B72\u3057\u307E\u305B\u3093\u3002
\r\n> LIKE\u3092\u542B\u3080SELECT\u306FFULL_SCAN\u306B\u306A\u308A\u307E\u3059\u3002AND\u3067\u4F75\u8A18\u3057\u305F\u5B89\u5168\u306A`$id`\u6761\u4EF6\u3001\u578B\u78BA\u8A8D\u6E08\u307FNUMBER\u6761\u4EF6\u3001\u5B9F\u5728\u78BA\u8A8D\u6E08\u307F\u9078\u629E\u7CFB`IN`\uFF0F`NOT IN`\u306F\u4E8B\u524D\u7D5E\u308A\u8FBC\u307F\u306B\u4F7F\u308F\u308C\u307E\u3059\u304C\u3001\u305D\u308C\u4EE5\u5916\u306F\u5168\u4EF6\u53D6\u5F97\u306B\u306A\u308A\u307E\u3059\u3002\u5927\u91CF\u30EC\u30B3\u30FC\u30C9\u3067\u306F\u8D70\u67FB\u4EF6\u6570\u304C`maxRecords`\u3078\u5230\u9054\u3057\u3001\u65E2\u5B9A\u3067\u306F\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002`onLimitReached = \"truncate\"`\u3092\u9078\u3076\u3068\u4E0A\u9650\u4EE5\u964D\u306E\u4E00\u81F4\u884C\u3092\u6B20\u843D\u3055\u305B\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002
\r\n> \u901A\u5E38\u306E\u89AA\u30EC\u30B3\u30FC\u30C9\u306B\u5BFE\u3059\u308B`UPDATE` / `DELETE`\u3067\u306F\u3001\u3059\u3079\u3066\u306E`LIKE` / `NOT LIKE`\u3092\u62D2\u5426\u3057\u307E\u3059\u3002\u5148\u306B\u4E0A\u9650\u30A8\u30E9\u30FC\u306E\u306A\u3044SELECT\u3067\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u756A\u53F7\u3092\u78BA\u8A8D\u3057\u3001`IN`\u307E\u305F\u306F\u5B8C\u5168\u4E00\u81F4\u6761\u4EF6\u3067\u5BFE\u8C61\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u30B5\u30D6\u30C6\u30FC\u30D6\u30EBDML\u306FJavaScript\u8A55\u4FA1\u7D4C\u8DEF\u306E\u305F\u3081\u5F93\u6765\u3069\u304A\u308A\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n### IS NULL / IS NOT NULL\r\n\r\nkintone \u3067\u306F\u7A7A\u6587\u5B57\uFF08`\"\"`\uFF09\u3092 NULL \u3068\u3057\u3066\u6271\u3044\u307E\u3059\u3002\r\n\r\n```sql\r\nWHERE \u5099\u8003 IS NULL -- \u5099\u8003\u304C\u7A7A\u306E\u30EC\u30B3\u30FC\u30C9\r\nWHERE \u62C5\u5F53\u8005 IS NOT NULL -- \u62C5\u5F53\u8005\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u308B\u30EC\u30B3\u30FC\u30C9\r\n```\r\n\r\n### \u8AD6\u7406\u6F14\u7B97\u5B50\r\n\r\n\u512A\u5148\u9806\u4F4D: `NOT` > `AND` > `OR`\r\n\r\n```sql\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5B8C\u4E86' AND \u91D1\u984D > 50000\r\nWHERE \u90E8\u7F72 = '\u55B6\u696D\u90E8' OR \u90E8\u7F72 = '\u958B\u767A\u90E8'\r\nWHERE NOT \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u30AD\u30E3\u30F3\u30BB\u30EB'\r\n```\r\n\r\n\u30AB\u30C3\u30B3\u3067\u512A\u5148\u9806\u4F4D\u3092\u660E\u793A\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nWHERE (\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5B8C\u4E86' OR \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u627F\u8A8D\u6E08') AND \u91D1\u984D > 10000\r\n```\r\n\r\n### WHERE \u3067\u306E\u95A2\u6570\u4F7F\u7528\r\n\r\nWHERE \u53E5\u306E\u5DE6\u8FBA\u306B\u95A2\u6570\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002 \r\n\u3053\u306E\u5834\u5408\u3001\u81EA\u52D5\u7684\u306B FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\u3002\r\n\r\n```sql\r\nWHERE UPPER(\u30B9\u30C6\u30FC\u30BF\u30B9) = 'ACTIVE'\r\nWHERE LOWER(\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9) LIKE '%@example.com'\r\nWHERE LENGTH(\u30B3\u30FC\u30C9) > 5\r\nWHERE TRIM(\u6C0F\u540D) != ''\r\nWHERE SUBSTRING(\u90F5\u4FBF\u756A\u53F7, 1, 3) = '100'\r\n```\r\n\r\n### kintone \u5C02\u7528\u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u610F\u5473 |\r\n|------|------|\r\n| `TODAY()` | \u4ECA\u65E5\u306E\u65E5\u4ED8\uFF08`YYYY-MM-DD` \u5F62\u5F0F\uFF09 |\r\n| `NOW()` | \u73FE\u5728\u65E5\u6642\uFF08ISO 8601 \u5F62\u5F0F\uFF09 |\r\n| `LOGINUSER()` | \u30ED\u30B0\u30A4\u30F3\u4E2D\u306E\u30E6\u30FC\u30B6\u30FC\uFF08kintone \u74B0\u5883\u306E\u307F\u6709\u52B9\uFF09 |\r\n\r\n```sql\r\nWHERE \u4F5C\u6210\u65E5\u6642 >= TODAY()\r\nWHERE \u671F\u9650\u65E5 < TODAY()\r\nWHERE \u62C5\u5F53\u8005 = LOGINUSER()\r\n```\r\n\r\n---", uri: "ksql://language-reference/06-where" }, "07-join": { heading: "7. JOIN", text: "## 7. JOIN\r\n\r\nINNER JOIN\u30FBLEFT JOIN\u30FBRIGHT JOIN \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u3059\u3002 \r\n\u8907\u6570\u306E JOIN \u3092\u9023\u9396\u3057\u3066 3\u30C6\u30FC\u30D6\u30EB\u4EE5\u4E0A\u306E\u7D50\u5408\u3082\u53EF\u80FD\u3067\u3059\u3002 \r\n\u7D50\u5408\u6761\u4EF6\u306F\u7B49\u5024\u7D50\u5408\uFF08`ON a.\u30D5\u30A3\u30FC\u30EB\u30C9 = b.\u30D5\u30A3\u30FC\u30EB\u30C9`\uFF09\u306E\u307F\u5BFE\u5FDC\u3002\r\n\r\n### INNER JOIN\r\n\r\n\u4E21\u30C6\u30FC\u30D6\u30EB\u3067\u7D50\u5408\u6761\u4EF6\u3092\u6E80\u305F\u3059\u884C\u306E\u307F\u8FD4\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT a.\u6C0F\u540D, b.\u5546\u54C1\u540D, b.\u91D1\u984D\r\nFROM APP100 AS a\r\nINNER JOIN APP200 AS b ON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n```\r\n\r\n`INNER` \u306F\u7701\u7565\u53EF\u80FD\uFF08`JOIN` \u306E\u307F\u3067 INNER JOIN \u6271\u3044\uFF09\u3002\r\n\r\n```sql\r\nFROM APP100 AS a\r\nJOIN APP200 AS b ON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n```\r\n\r\n### LEFT JOIN\r\n\r\n\u5DE6\u30C6\u30FC\u30D6\u30EB\u306E\u5168\u884C + \u7D50\u5408\u6761\u4EF6\u3092\u6E80\u305F\u3059\u53F3\u30C6\u30FC\u30D6\u30EB\u306E\u884C\u3092\u8FD4\u3057\u307E\u3059\u3002 \r\n\u53F3\u30C6\u30FC\u30D6\u30EB\u306B\u30DE\u30C3\u30C1\u3057\u306A\u3044\u5834\u5408\u3001\u53F3\u5074\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u7A7A\u6587\u5B57\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT a.\u6C0F\u540D, b.\u91D1\u984D\r\nFROM APP100 AS a\r\nLEFT JOIN APP200 AS b ON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n```\r\n\r\n### RIGHT JOIN\r\n\r\n\u53F3\u30C6\u30FC\u30D6\u30EB\u306E\u5168\u884C + \u7D50\u5408\u6761\u4EF6\u3092\u6E80\u305F\u3059\u5DE6\u30C6\u30FC\u30D6\u30EB\u306E\u884C\u3092\u8FD4\u3057\u307E\u3059\u3002 \r\n\u5DE6\u30C6\u30FC\u30D6\u30EB\u306B\u30DE\u30C3\u30C1\u3057\u306A\u3044\u5834\u5408\u3001\u5DE6\u5074\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u7A7A\u6587\u5B57\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT a.\u91D1\u984D, b.\u9867\u5BA2\u540D\r\nFROM APP100 AS a\r\nRIGHT JOIN APP200 AS b ON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n```\r\n\r\n### 3\u30C6\u30FC\u30D6\u30EB\u4EE5\u4E0A\u306E JOIN\uFF08\u8907\u6570 JOIN \u9023\u9396\uFF09\r\n\r\n```sql\r\nSELECT a.\u6C0F\u540D, b.\u5546\u54C1\u540D, c.\u914D\u9001\u5148\r\nFROM APP100 AS a\r\nINNER JOIN APP200 AS b ON a.\u6CE8\u6587ID = b.\u6CE8\u6587ID\r\nLEFT JOIN APP300 AS c ON a.\u914D\u9001ID = c.\u914D\u9001ID\r\n```\r\n\r\n> **\u6CE8\u610F:** JOIN \u3092\u4F7F\u3046\u3068\u5168\u4EF6\u53D6\u5F97\uFF08FULL_SCAN \u30E2\u30FC\u30C9\uFF09\u306B\u306A\u308B\u305F\u3081\u3001 \r\n> \u5927\u91CF\u30EC\u30B3\u30FC\u30C9\u306E\u5834\u5408\u306F\u30D1\u30D5\u30A9\u30FC\u30DE\u30F3\u30B9\u306B\u6CE8\u610F\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n---", uri: "ksql://language-reference/07-join" }, "08-group-by-aggregates": { heading: "8. GROUP BY / \u96C6\u8A08\u95A2\u6570", text: '## 8. GROUP BY / \u96C6\u8A08\u95A2\u6570\r\n\r\n### GROUP BY\r\n\r\n```sql\r\nSELECT \u90E8\u7F72, COUNT(*) AS \u4EF6\u6570\r\nFROM APP100\r\nGROUP BY \u90E8\u7F72\r\n```\r\n\r\n```sql\r\nSELECT \u62C5\u5F53\u8005, \u30B9\u30C6\u30FC\u30BF\u30B9, SUM(\u91D1\u984D) AS \u5408\u8A08\r\nFROM APP100\r\nGROUP BY \u62C5\u5F53\u8005, \u30B9\u30C6\u30FC\u30BF\u30B9\r\n```\r\n\r\n### \u96C6\u8A08\u95A2\u6570\r\n\r\n| \u95A2\u6570 | \u610F\u5473 | NULL/\u7A7A\u306E\u6271\u3044 |\r\n|------|------|---------------|\r\n| `COUNT(*)` | \u5168\u884C\u6570 | NULL \u3092\u542B\u3080\u5168\u884C\u3092\u6570\u3048\u308B |\r\n| `COUNT(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u7A7A\u3067\u306A\u3044\u884C\u6570 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `SUM(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5408\u8A08 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `AVG(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u5E73\u5747 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `MAX(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u6700\u5927\u5024 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `MIN(\u30D5\u30A3\u30FC\u30EB\u30C9)` | \u6700\u5C0F\u5024 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `GROUP_CONCAT([DISTINCT] \u5F15\u6570 [SEPARATOR \'\u533A\u5207\u308A\'])` | \u6587\u5B57\u5217\u9023\u7D50 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `VAR_POP([DISTINCT] \u5F15\u6570)` | \u6BCD\u96C6\u56E3\u5206\u6563 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `VAR_SAMP([DISTINCT] \u5F15\u6570)` | \u6A19\u672C\u5206\u6563 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `STDDEV_POP([DISTINCT] \u5F15\u6570)` | \u6BCD\u96C6\u56E3\u6A19\u6E96\u504F\u5DEE | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `STDDEV_SAMP([DISTINCT] \u5F15\u6570)` | \u6A19\u672C\u6A19\u6E96\u504F\u5DEE | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `MEDIAN([DISTINCT] \u5F15\u6570)` | \u4E2D\u592E\u5024 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u30B9\u30AD\u30C3\u30D7 |\r\n| `MODE(\u5F15\u6570)` | \u6700\u983B\u5024 | \u7A7A\u6587\u5B57\u30FBNULL \u306F\u5019\u88DC\u304B\u3089\u9664\u5916 |\r\n\r\n> **`MAX`/`MIN`/`MODE` \u306E\u6BD4\u8F03\u898F\u5247**: \u5B9F\u30A2\u30D7\u30EA\u306E NUMBER \u3068\u6570\u5024\u5F62\u5F0F CALC \u306F\u6570\u5024\u9806\u3001\u30C6\u30AD\u30B9\u30C8\u30FB\u9078\u629E\u30FB\u65E5\u6642\u30D5\u30A3\u30FC\u30EB\u30C9\u3068\u6587\u5B57\u5217\u5F62\u5F0F CALC \u306F\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3001\u9078\u629E\u80A2\u30FBSTATUS \u306F\u5B9A\u7FA9\u9806\u3067\u6BD4\u8F03\u3057\u307E\u3059\u3002\u65E5\u6642\u306E\u6642\u7CFB\u5217\u9806\u3068\u4E00\u81F4\u3059\u308B\u306E\u306F kintone \u304C\u8FD4\u3059\u6B63\u898F\u5316\u5F62\u5F0F\uFF08DATE=`YYYY-MM-DD`\u3001TIME=`HH:mm`\u3001DATETIME/\u4F5C\u6210\u65E5\u6642/\u66F4\u65B0\u65E5\u6642=`...Z`\uFF09\u304C\u524D\u63D0\u3067\u3059\u3002\u78BA\u5B9A\u3067\u304D\u305F\u578B\u30E1\u30BF\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB/CTE\u306B\u3082\u4F1D\u64AD\u3057\u307E\u3059\u3002`MODE` \u306E\u7B97\u8853\u5F0F\u5F15\u6570\u306F\u6570\u5024\u9806\u3001\u578B\u30E1\u30BF\u4E0D\u660E\u306E\u76F4\u63A5\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u306F\u5B89\u5168\u5074\u306E\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3067\u3059\u3002\r\n\r\n```sql\r\nSELECT COUNT(*) AS \u7DCF\u4EF6\u6570, SUM(\u91D1\u984D) AS \u5408\u8A08\u91D1\u984D, AVG(\u91D1\u984D) AS \u5E73\u5747\u91D1\u984D\r\nFROM APP100\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = \'\u5B8C\u4E86\'\r\n```\r\n\r\n### GROUP_CONCAT\r\n\r\n`GROUP_CONCAT` \u306F\u30B0\u30EB\u30FC\u30D7\u5185\u306E\u7A7A\u3067\u306A\u3044\u5024\u3092\u53CE\u96C6\u9806\u306B\u9023\u7D50\u3057\u307E\u3059\u3002\u65E2\u5B9A\u306E\u533A\u5207\u308A\u6587\u5B57\u306F `,` \u3067\u3059\u3002\r\n\r\n```sql\r\nSELECT \u9867\u5BA2ID, GROUP_CONCAT(\u62C5\u5F53\u8005) AS \u62C5\u5F53\u8005\u4E00\u89A7\r\nFROM APP100 GROUP BY \u9867\u5BA2ID\r\n\r\nSELECT \u9867\u5BA2ID, GROUP_CONCAT(DISTINCT \u696D\u7A2E SEPARATOR \' / \') AS \u696D\u7A2E\u4E00\u89A7\r\nFROM APP100 GROUP BY \u9867\u5BA2ID\r\n```\r\n\r\n- `DISTINCT` \u306F\u6587\u5B57\u5217\u3068\u3057\u3066\u91CD\u8907\u3092\u9664\u304D\u3001\u6700\u521D\u306B\u73FE\u308C\u305F\u9806\u5E8F\u3092\u4FDD\u3061\u307E\u3059\r\n- `SEPARATOR` \u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u3060\u3051\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002`SEPARATOR \'\'` \u306F\u533A\u5207\u308A\u306A\u3057\u3067\u3059\r\n- `GROUP_CONCAT(*)` \u3068 `GROUP_CONCAT(DISTINCT *)` \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\r\n- \u95A2\u6570\u5185\u306E `ORDER BY` \u306F\u672A\u5BFE\u5FDC\u3067\u3059\u3002\u9023\u7D50\u9806\u306F WHERE / JOIN \u9069\u7528\u5F8C\u306E\u53CE\u96C6\u9806\u3067\u3042\u308A\u3001\u53D6\u5F97\u9806\u304C\u5909\u308F\u308C\u3070\u7D50\u679C\u3082\u5909\u308F\u308A\u5F97\u307E\u3059\r\n- \u7D50\u679C\u3092\u9577\u3055\u3067\u5207\u308A\u6368\u3066\u307E\u305B\u3093\u3002\u66F8\u304D\u8FBC\u307F\u5148\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u6700\u5927\u6587\u5B57\u6570\u3092\u8D85\u3048\u305F\u5834\u5408\u306F\u66F8\u304D\u8FBC\u307F\u6642\u306E\u691C\u8A3C\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\r\n- `GROUP_CONCAT` \u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F `` `GROUP_CONCAT` `` \u3068\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\u3002`SEPARATOR` \u306F\u901A\u5E38\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u540D\u3068\u3057\u3066\u3082\u4F7F\u3048\u307E\u3059\r\n\r\n### \u7D71\u8A08\u96C6\u7D04\r\n\r\n`VAR_POP` / `VAR_SAMP` / `STDDEV_POP` / `STDDEV_SAMP` / `MEDIAN` \u306F\u6570\u5024\u5206\u5E03\u3092\u3001`MODE` \u306F\u6587\u5B57\u5217\u306E\u5B8C\u5168\u4E00\u81F4\u5358\u4F4D\u3067\u6700\u983B\u5024\u3092\u96C6\u8A08\u3057\u307E\u3059\u3002\u5206\u6563\u3068\u6A19\u6E96\u504F\u5DEE\u306F Welford \u6CD5\u3001\u4E2D\u592E\u5024\u306F\u6570\u5024\u6607\u9806\u3067\u6C42\u3081\u307E\u3059\u3002\u5076\u6570\u4EF6\u306E\u4E2D\u592E\u5024\u306F\u4E2D\u592E 2 \u5024\u306E binary64 \u5E73\u5747\u3067\u3059\u3002\r\n\r\n```sql\r\nSELECT \u90E8\u7F72, STDDEV_SAMP(\u91D1\u984D) AS \u6A19\u6E96\u504F\u5DEE, MEDIAN(\u91D1\u984D) AS \u4E2D\u592E\u5024\r\nFROM APP100\r\nGROUP BY \u90E8\u7F72\r\n\r\nSELECT \u90E8\u7F72, MODE(\u30B9\u30C6\u30FC\u30BF\u30B9) AS \u6700\u983B\u30B9\u30C6\u30FC\u30BF\u30B9\r\nFROM APP100\r\nGROUP BY \u90E8\u7F72\r\n```\r\n\r\n- \u53CE\u96C6\u3057\u305F\u5024\u306B\u6570\u5024\u5316\u3067\u304D\u306A\u3044\u5024\u307E\u305F\u306F `Infinity` / `-Infinity` \u304C\u3042\u308C\u3070 `ArgumentError` \u306B\u306A\u308A\u307E\u3059\r\n- 6 \u95A2\u6570\u306F\u5B8C\u5168\u5165\u529B\u3092\u5FC5\u8981\u3068\u3057\u307E\u3059\u3002`onLimit=truncate` \u3092\u6307\u5B9A\u3057\u3066\u3082\u4E0A\u9650\u5230\u9054\u6642\u306F\u30A8\u30E9\u30FC\u3068\u306A\u308A\u3001\u90E8\u5206\u96C6\u5408\u306E\u7D71\u8A08\u5024\u3092\u8FD4\u3057\u307E\u305B\u3093\r\n- `DISTINCT` \u306F Number \u5316\u5F8C\u306E\u6570\u5024\u540C\u5024\u3067\u91CD\u8907\u3092\u9664\u304D\u307E\u3059\u3002\u305F\u3068\u3048\u3070 `"1"` \u3068 `"01"` \u306F\u540C\u3058\u5024\u3067\u3059\u3002\u65E2\u5B58\u306E 6 \u96C6\u8A08\uFF08`COUNT` / `SUM` / `AVG` / `MIN` / `MAX` / `GROUP_CONCAT`\uFF09\u306F\u5F93\u6765\u3069\u304A\u308A\u6587\u5B57\u5217\u5358\u4F4D\u3067\u3059\r\n- `*` \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002\u5F15\u6570\u306B\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u307E\u305F\u306F\u7B97\u8853\u5F0F\u3092 1 \u3064\u6307\u5B9A\u3057\u307E\u3059\r\n- `MODE` \u306E\u540C\u983B\u5EA6\u5019\u88DC\u306F\u5F15\u6570\u578B\u306E canonical \u9806\u3067\u6700\u5C0F\u306E\u5024\u3092\u9078\u3073\u307E\u3059\u3002canonical \u540C\u5024\uFF08\u6570\u5024\u5217\u306E `"1"` \u3068 `"01"` \u306A\u3069\uFF09\u306F raw \u6587\u5B57\u5217\u306E\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3092\u4E8C\u6B21\u30AD\u30FC\u306B\u3059\u308B\u305F\u3081\u3001\u5165\u529B\u9806\u306B\u3088\u3089\u305A\u6C7A\u5B9A\u7684\u3067\u3059\r\n- `MODE` \u306F\u672A\u9078\u629E\uFF08\u7A7A\u30BB\u30EB\uFF09\u3092\u5019\u88DC\u306B\u542B\u3081\u307E\u305B\u3093\u3002\u672A\u9078\u629E\u4EF6\u6570\u306F `COUNT(*) - COUNT(\u30D5\u30A3\u30FC\u30EB\u30C9)` \u3067\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\r\n- `MODE(DISTINCT x)` \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002`MODE(COALESCE(\u30D5\u30A3\u30FC\u30EB\u30C9, \'\u672A\u9078\u629E\'))` \u3082\u7B97\u8853\u5F0F\u6271\u3044\u3067\u6570\u5024\u8A55\u4FA1\u3055\u308C\u308B\u305F\u3081\u3001\u672A\u9078\u629E\u3092\u30AB\u30C6\u30B4\u30EA\u5316\u3059\u308B\u7528\u9014\u306B\u306F\u4F7F\u3048\u307E\u305B\u3093\u3002\u5FC5\u8981\u306A\u3089 CTE \u307E\u305F\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3067\u6587\u5B57\u5217\u5217\u3068\u3057\u3066\u5B9F\u4F53\u5316\u3057\u3066\u304B\u3089 `MODE` \u3092\u9069\u7528\u3057\u3066\u304F\u3060\u3055\u3044\r\n- \u7121\u5370\u306E `STDDEV` / `VARIANCE` \u306F\u5225\u540D\u3067\u306F\u306A\u304F\u975E\u5BFE\u5FDC\u3067\u3059\u3002\u6BCD\u96C6\u56E3\u30FB\u6A19\u672C\u306E\u3069\u3061\u3089\u304B\u304C\u65B9\u8A00\u3067\u7570\u306A\u308B\u305F\u3081\u3001`_POP` / `_SAMP` \u3092\u660E\u793A\u3057\u3066\u304F\u3060\u3055\u3044\r\n- 6 \u95A2\u6570\u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002`MODE` \u3092\u542B\u3080\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F `` `MODE` `` \u306E\u3088\u3046\u306B\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u3067\u56F2\u307F\u307E\u3059\u3002`MODEL` \u306A\u3069\u9577\u3044\u8B58\u5225\u5B50\u306F\u5F71\u97FF\u3092\u53D7\u3051\u307E\u305B\u3093\r\n\r\n### DISTINCT \u4ED8\u304D\u96C6\u8A08\r\n\r\n```sql\r\nSELECT COUNT(DISTINCT \u62C5\u5F53\u8005) AS \u62C5\u5F53\u8005\u6570 FROM APP100\r\nSELECT COUNT(DISTINCT \u90FD\u9053\u5E9C\u770C) AS \u90FD\u9053\u5E9C\u770C\u6570 FROM APP100\r\n```\r\n\r\n### 0 \u4EF6\u6642\u306E\u6319\u52D5\r\n\r\nGROUP BY \u306E\u306A\u3044\u96C6\u8A08\u30AF\u30A8\u30EA\u306F\u3001\u5BFE\u8C61\u304C 0 \u4EF6\u3067\u3082**\u5E38\u306B 1 \u884C**\u3092\u8FD4\u3057\u307E\u3059\uFF08SQL \u6A19\u6E96\u6E96\u62E0\uFF09\u3002\r\n\r\n```sql\r\n-- \u8A72\u5F53 0 \u4EF6\u3067\u3082\u300CCOUNT(*) = 0\u300D\u306E 1 \u884C\u304C\u8FD4\u308B\r\nSELECT COUNT(*) FROM APP100 WHERE \u7570\u5E38\u30D5\u30E9\u30B0 = \'1\'\r\n```\r\n\r\n| \u96C6\u8A08 | 0 \u4EF6\u6642\u306E\u5024 |\r\n|------|-----------|\r\n| `COUNT(*)` / `COUNT(f)` / `COUNT(DISTINCT f)` | `0` |\r\n| `SUM` / `AVG` / `MAX` / `MIN` | `0`\uFF08**\u6A19\u6E96 SQL \u306E NULL \u3068\u306F\u7570\u306A\u308A\u307E\u3059**\uFF09 |\r\n| `GROUP_CONCAT` | `""`\uFF08\u7A7A\u6587\u5B57\uFF09 |\r\n| `VAR_POP` / `STDDEV_POP` / `VAR_SAMP` / `STDDEV_SAMP` / `MEDIAN` | `""`\uFF08\u7A7A\u6587\u5B57\uFF09 |\r\n| `MODE` | `""`\uFF08\u7A7A\u6587\u5B57\uFF09 |\r\n\r\n- \u300C\u5BFE\u8C61\u306A\u3057\uFF08COUNT = 0\uFF09\u300D\u3068\u300C\u5408\u8A08\u304C 0\u300D\u3092\u533A\u5225\u3057\u305F\u3044\u5834\u5408\u306F COUNT \u3092\u4F75\u7528\u3057\u3066\u304F\u3060\u3055\u3044\r\n- GROUP BY \u304C**\u3042\u308B**\u5834\u5408\u306F\u5F93\u6765\u3069\u304A\u308A 0 \u884C\u3092\u8FD4\u3057\u307E\u3059\uFF08\u30B0\u30EB\u30FC\u30D7\u304C\u5B58\u5728\u3057\u306A\u3044\u305F\u3081\uFF09\r\n- 1 \u4EF6\u3060\u3051\u306E\u30B0\u30EB\u30FC\u30D7\u3067\u306F `VAR_SAMP` / `STDDEV_SAMP` \u306F\u7A7A\u6587\u5B57\u3001`VAR_POP` / `STDDEV_POP` \u306F `0`\u3001`MEDIAN` \u306F\u305D\u306E\u5024\u3067\u3059\r\n- 1 \u4EF6\u3060\u3051\u306E `MODE` \u306F\u305D\u306E\u5024\u3001\u5168\u4EF6\u304C\u7A7A\u30BB\u30EB\u306A\u3089\u7A7A\u6587\u5B57\u3067\u3059\r\n- \u3053\u308C\u306B\u3088\u308A ASSERT \u306E\u5065\u5168\u6027\u30C1\u30A7\u30C3\u30AF `ASSERT (SELECT COUNT(*) ... WHERE \u7570\u5E38\u6761\u4EF6) = 0` \u304C\u8A72\u5F53 0 \u4EF6\uFF08\u5065\u5168\u6642\uFF09\u306B\u6210\u7ACB\u3057\u307E\u3059\uFF08\xA726 ASSERT\uFF09\r\n\r\n---', uri: "ksql://language-reference/08-group-by-aggregates" }, "09-having": { heading: "9. HAVING", text: "## 9. HAVING\r\n\r\nGROUP BY \u5F8C\u306E\u96C6\u8A08\u7D50\u679C\u306B\u5BFE\u3057\u3066\u30D5\u30A3\u30EB\u30BF\u3092\u304B\u3051\u307E\u3059\u3002 \r\nHAVING \u53E5\u306B\u306F\u96C6\u8A08\u95A2\u6570\u30FBGROUP BY \u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n\u76F4\u63A5\u8A18\u8FF0\u3057\u305F\u96C6\u8A08\u95A2\u6570\u306F\u3001\u540C\u3058\u96C6\u8A08\u304C SELECT \u5217\u306B\u3082\u5B58\u5728\u3059\u308B\u5834\u5408\u306B\u9650\u308A\u8A55\u4FA1\u3067\u304D\u307E\u3059\u3002SELECT \u306B\u306A\u3044\u96C6\u8A08\u3092 HAVING \u5C02\u7528\u3067\u8FFD\u52A0\u8A08\u7B97\u306F\u3057\u307E\u305B\u3093\u3002\u5F0F\u5F15\u6570\u306E\u7D71\u8A08\u91CF\u306F SELECT \u3067 alias \u3092\u4ED8\u3051\u3001\u305D\u306E alias \u3092 HAVING \u304B\u3089\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n```sql\r\nSELECT \u90E8\u7F72, COUNT(*) AS \u4EF6\u6570\r\nFROM APP100\r\nGROUP BY \u90E8\u7F72\r\nHAVING COUNT(*) >= 5\r\n```\r\n\r\n```sql\r\nSELECT \u62C5\u5F53\u8005, SUM(\u91D1\u984D) AS \u5408\u8A08\r\nFROM APP100\r\nGROUP BY \u62C5\u5F53\u8005\r\nHAVING SUM(\u91D1\u984D) > 1000000\r\n```\r\n\r\nWHERE \u3068\u306E\u9055\u3044:\r\n- `WHERE` \u2014 \u96C6\u8A08\u524D\u306E\u30EC\u30B3\u30FC\u30C9\u306B\u5BFE\u3057\u3066\u30D5\u30A3\u30EB\u30BF\r\n- `HAVING` \u2014 \u96C6\u8A08\u5F8C\u306E\u30B0\u30EB\u30FC\u30D7\u306B\u5BFE\u3057\u3066\u30D5\u30A3\u30EB\u30BF\r\n\r\n```sql\r\nSELECT \u62C5\u5F53\u8005, COUNT(*) AS \u4EF6\u6570\r\nFROM APP100\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5B8C\u4E86' -- \u96C6\u8A08\u524D\u30D5\u30A3\u30EB\u30BF\r\nGROUP BY \u62C5\u5F53\u8005\r\nHAVING COUNT(*) >= 3 -- \u96C6\u8A08\u5F8C\u30D5\u30A3\u30EB\u30BF\r\n```\r\n\r\n---", uri: "ksql://language-reference/09-having" }, "10-order-by": { heading: "10. ORDER BY", text: '## 10. ORDER BY\r\n\r\n### \u57FA\u672C\r\n\r\n```sql\r\nSELECT * FROM APP100\r\nORDER BY \u4F5C\u6210\u65E5\u6642 DESC\r\n\r\nSELECT * FROM APP100\r\nORDER BY \u90E8\u7F72 ASC, \u91D1\u984D DESC\r\n```\r\n\r\n- `ASC` \u2014 \u6607\u9806\uFF08\u7701\u7565\u53EF\u3001\u30C7\u30D5\u30A9\u30EB\u30C8\uFF09\r\n- `DESC` \u2014 \u964D\u9806\r\n\r\n### SELECT alias \u306B\u3088\u308B\u30BD\u30FC\u30C8\r\n\r\n\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E\u901A\u5E38 `ORDER BY` \u3067\u306F\u3001SELECT \u51FA\u529B alias \u3092\u30AD\u30FC\u3068\u3057\u3066\u53C2\u7167\u3067\u304D\u307E\u3059\u3002alias \u306E\u5024\u306F SELECT \u5F0F\u3068\u540C\u3058\u898F\u5247\u30FB\u578B\u3067\u8A55\u4FA1\u3057\u3066\u304B\u3089\u30BD\u30FC\u30C8\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT \u91D1\u984D AS amount\r\nFROM APP100\r\nORDER BY amount DESC\r\n\r\nSELECT DAYOFWEEK(\u65E5\u4ED8) AS weekday\r\nFROM APP100\r\nORDER BY weekday ASC\r\n```\r\n\r\n- ORDER BY \u540D\u304C SELECT alias \u3068\u5165\u529B\u884C\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u4E21\u65B9\u306B\u5B8C\u5168\u4E00\u81F4\u3059\u308B\u5834\u5408\u306F\u3001**SELECT alias \u3092\u512A\u5148**\u3057\u307E\u3059\u3002\u30C9\u30C3\u30C8\u3092\u542B\u3080 alias \u3082\u5B8C\u5168\u4E00\u81F4\u3092\u5148\u306B\u5224\u5B9A\u3059\u308B\u305F\u3081\u3001\u540C\u540D\u306E\u4FEE\u98FE\u7269\u7406\u5217\u306B\u306F\u305D\u306E ORDER BY \u304B\u3089\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\r\n- \u540C\u3058 alias \u3092\u8907\u6570\u306E SELECT \u5217\u3078\u6307\u5B9A\u3057\u305F\u5834\u5408\u306F\u3001\u51FA\u529B\u3068\u540C\u3058\u304F**\u5F8C\u306B\u8A18\u8FF0\u3057\u305F\u5217\u304C\u512A\u5148**\u3055\u308C\u307E\u3059\r\n- alias \u306B\u4E00\u81F4\u3057\u306A\u3044\u540D\u524D\u306F\u5F93\u6765\u3069\u304A\u308A\u5165\u529B\u884C\u30D5\u30A3\u30FC\u30EB\u30C9\u3068\u3057\u3066\u89E3\u6C7A\u3057\u307E\u3059\u3002\u3069\u3061\u3089\u306B\u3082\u89E3\u6C7A\u3067\u304D\u306A\u3044\u540D\u524D\u306F `ORDER_KEY_UNRESOLVED` \u3067\u5B9F\u884C\u524D\u306B\u62D2\u5426\u3057\u307E\u3059\r\n- \u3053\u306E alias \u89E3\u6C7A\u306F\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E\u901A\u5E38 `ORDER BY` \u3060\u3051\u306B\u9069\u7528\u3057\u307E\u3059\u3002`OVER (ORDER BY ...)` \u304B\u3089\u540C\u4E00 SELECT \u306E alias \u306F\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\u3002\u5FC5\u8981\u306A\u5834\u5408\u306F CTE \u307E\u305F\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3067\u4E00\u5EA6\u5217\u3092\u5B9F\u4F53\u5316\u3057\u3066\u304F\u3060\u3055\u3044\r\n- `KORDER BY` \u306F SELECT alias \u3092\u76F4\u63A5\u7269\u7406\u5217\u3068\u3057\u3066\u6271\u3044\u307E\u305B\u3093\r\n\r\n### canonical\u9806\uFF08v3.0.0\uFF09\r\n\r\n\u901A\u5E38\u306E`ORDER BY`\u306F\u3001REST\u53D6\u5F97\u30FBFULL_SCAN\u30FB\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30FBCLI\u30FBMCP\u30FB\u30D7\u30E9\u30B0\u30A4\u30F3\u306E\u3069\u306E\u7D4C\u8DEF\u3067\u3082\u3001\u540C\u3058kSQL canonical\u6BD4\u8F03\u898F\u5247\u3092\u4F7F\u3044\u307E\u3059\u3002\r\n\r\n- typed string\uFF0F\u578B\u4E0D\u660E: Unicode\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3002NFC/NFD\u7B49\u306EUnicode\u6B63\u898F\u5316\u3084\u30ED\u30B1\u30FC\u30EB\u7167\u5408\u306F\u884C\u3044\u307E\u305B\u3093\r\n- typed number: `\u7A7A\u30BB\u30EB < -Infinity < \u6709\u9650\u6570 < +Infinity < "NaN" < \u305D\u306E\u4ED6\u975E\u6570\u5024`\u3002\u305D\u306E\u4ED6\u975E\u6570\u5024\u306E\u30D0\u30F3\u30C9\u5185\u306F\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3067\u3059\r\n- \u9078\u629E\u7CFB: \u30D5\u30A9\u30FC\u30E0\u307E\u305F\u306F\u30D7\u30ED\u30BB\u30B9\u8A2D\u5B9A\u306E\u5B9A\u7FA9\u9806\u3002\u672A\u77E5\u30FB\u524A\u9664\u6E08\u307F\u9078\u629E\u80A2\u306F\u65E2\u77E5\u5024\u306E\u5F8C\u308D\u3067\u3059\r\n- RECORD_NUMBER: \u30A2\u30D7\u30EA\u30B3\u30FC\u30C9\u3092\u542B\u3080\u8868\u793A\u5024\u304B\u3089\u672B\u5C3E\u306E\u6570\u5024ID\u3092\u4EFB\u610F\u7CBE\u5EA6\u3067\u6BD4\u8F03\u3057\u307E\u3059\r\n- DESC\u306F\u30D0\u30F3\u30C9\u3092\u542B\u3080\u9806\u5E8F\u5168\u4F53\u3092\u53CD\u8EE2\u3057\u307E\u3059\r\n\r\n\u6587\u5B57\u5217`"10"`\u3092\u6570\u502410\u3068\u3057\u3066\u6271\u3046\u5024\u30D9\u30FC\u30B9\u81EA\u52D5\u5224\u5B9A\u306F\u884C\u3044\u307E\u305B\u3093\u3002\u578B\u3092\u78BA\u5B9A\u3067\u304D\u306A\u3044\u5F0F\u30FB\u4E00\u6642\u5217\u3082\u65E2\u5B9A\u306F\u6587\u5B57\u5217\u3067\u3059\u3002\u30ED\u30FC\u30AB\u30EB\u6BD4\u8F03\u5951\u7D04\u306E\u306A\u3044\u8907\u5408\u578B\u306F\u3001\u884C\u6570\u306B\u4F9D\u5B58\u305B\u305Aplanning\u6642\u306B\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n\u540C\u5024\u884C\u306E\u6700\u7D42\u8868\u793A\u9806\u306Fcanonical tie\u3068\u3057\u3066\u5B89\u5B9A\u5316\u3057\u307E\u3059\u304C\u3001`RANK` / `DENSE_RANK`\u306Epeer\u5224\u5B9A\u306B\u306F\u305D\u306Etie\u3092\u6DF7\u305C\u307E\u305B\u3093\u3002JOIN\u3067\u8907\u6570\u30C6\u30FC\u30D6\u30EB\u306B\u540C\u540D\u5217\u304C\u3042\u308B\u5834\u5408\u3001\u975E\u4FEE\u98FE\u30AD\u30FC\u306F`ambiguous column`\u3068\u3057\u3066\u62D2\u5426\u3059\u308B\u305F\u3081\u3001`a.\u5217\u540D`\u306E\u3088\u3046\u306B\u4FEE\u98FE\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n### \u7B97\u8853\u5F0F\u30FB\u95A2\u6570\u306B\u3088\u308B\u30BD\u30FC\u30C8\r\n\r\nORDER BY \u306E\u30AD\u30FC\u306B\u7B97\u8853\u5F0F\u3084\u95A2\u6570\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002 \r\n\u3053\u306E\u5834\u5408\u3001\u81EA\u52D5\u7684\u306B FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u7B97\u8853\u5F0F\r\nORDER BY \u5358\u4FA1 * \u6570\u91CF DESC\r\nORDER BY (\u58F2\u4E0A - \u539F\u4FA1) / \u58F2\u4E0A DESC\r\n\r\n-- \u95A2\u6570\r\nORDER BY UPPER(\u9867\u5BA2\u540D) ASC\r\nORDER BY LENGTH(\u6C0F\u540D) ASC\r\nORDER BY ROUND(\u91D1\u984D, -3) DESC\r\n```\r\n\r\n### KORDER BY\uFF08kintone\u56FA\u6709\u9806\u3001v3.0.0\uFF09\r\n\r\n`KORDER BY`\u306F\u9AD8\u901F\u5316\u30D2\u30F3\u30C8\u3067\u306F\u306A\u304F\u3001\u6BD4\u8F03\u610F\u5473\u3092kintone REST API\u306E\u578B\u5225\u9806\u5E8F\u3078\u5207\u308A\u66FF\u3048\u308B\u5225\u69CB\u6587\u3067\u3059\u3002\u6761\u4EF6\u5916\u3067\u901A\u5E38`ORDER BY`\u3078\u9ED9\u3063\u3066\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u305B\u3093\u3002\r\n\r\n```sql\r\nSELECT \u4F1A\u793E\u540D, \u91D1\u984D\r\nFROM APP100\r\nWHERE \u9867\u5BA2\u30E9\u30F3\u30AF = \'A\'\r\nKORDER BY \u4F1A\u793E\u540D ASC, $id ASC\r\nLIMIT 20\r\n```\r\n\r\n\u521D\u671F\u7248\u306F\u6B21\u3092\u3059\u3079\u3066\u6E80\u305F\u3059\u5834\u5408\u3060\u3051\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n- \u5229\u7528\u8005\u3078\u7D50\u679C\u3092\u8FD4\u3059\u30C8\u30C3\u30D7\u30EC\u30D9\u30EBSELECT\u3001\u5358\u4E00\u306E\u7269\u7406\u30A2\u30D7\u30EA\u3001JOIN\uFF0FCTE\uFF0Ftemp\uFF0FUNION\uFF0F\u96C6\u7D04\uFF0FWINDOW\u306A\u3057\r\n- **\u975E\u4FEE\u98FE\u306E**\u76F4\u63A5\u7269\u7406\u30D5\u30A3\u30FC\u30EB\u30C9\u307E\u305F\u306F`$id`\u3060\u3051\u3092\u30AD\u30FC\u306B\u3059\u308B\u3002SELECT alias\u3001`t.\u91D1\u984D`\u306E\u3088\u3046\u306A\u8868\u4FEE\u98FE\u3001\u95A2\u6570\u3001\u7B97\u8853\u5F0F\u306F\u672A\u5BFE\u5FDC\r\n- WHERE\u5168\u4F53\u3092kintone\u3078\u540C\u5024\u306B\u62BC\u3057\u4E0B\u3052\u3089\u308C\u3001SQL `LIKE`\uFF0F`KLIKE`\u3092\u542B\u307E\u306A\u3044\r\n- `LIMIT`\u3092\u660E\u793A\u3057\u3001`LIMIT`\u30FB`OFFSET`\u30FB`OFFSET + LIMIT`\u304C\u3059\u3079\u30660\u4EE5\u4E0A\u306E\u5B89\u5168\u306A\u6574\u6570\u3067\u3042\u308B\r\n- \u578B\u306F`$id`\u3001RECORD_NUMBER\u3001SINGLE_LINE_TEXT\u3001NUMBER\u3001CALC\u3001DATE\u3001DATETIME\u3001TIME\u3001CREATED_TIME\u3001UPDATED_TIME\u3001DROP_DOWN\u3001RADIO_BUTTON\u3001STATUS\u3001LINK\u3001CREATOR\u3001MODIFIER\u306E\u660E\u793Aallowlist\u5185\r\n\r\n`LIMIT \u2264 500`\u30FB`OFFSET \u2264 10000`\u30FB`LIMIT \u2264 maxRecords`\u306A\u3089\u3001\u6307\u5B9A\u3057\u305FORDER/LIMIT/OFFSET\u3092\u5358\u767AGET\u3078\u305D\u306E\u307E\u307E\u9001\u308A\u307E\u3059\u3002`LIMIT 0`\u3082\u578B\u30FBWHERE\u30FBquery\u5F62\u72B6\u3092\u5B8C\u5168\u691C\u67FB\u3057\u305F\u5F8C\u3001records API\u3092\u547C\u3070\u305A\u7A7A\u7D50\u679C\u3092\u8FD4\u3057\u307E\u3059\u3002\u540C\u5024\u7FA4\u306E\u6C7A\u5B9A\u6027\u304C\u5FC5\u8981\u306A\u3089\u3001\u6700\u5F8C\u306E\u30AD\u30FC\u3068\u3057\u3066`$id ASC`\u7B49\u3092\u660E\u793A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n#### \u5927\u304D\u3044\u7A93\u3068 Cursor API\uFF08v3.1.0\uFF09\r\n\r\nv3.0.0 \u3067\u306F\u5358\u767AGET\u3067\u5B8C\u7D50\u3057\u306A\u3044\u7A93\uFF08`LIMIT > 500`\u30FB`OFFSET > 10000`\uFF09\u306F planning error \u3067\u3059\u3002**v3.1.0** \u3067\u306F\u3001\u3053\u306E\u7A93\u3092 kintone \u306E **Cursor API**\uFF08\u30AB\u30FC\u30BD\u30EB\u4F5C\u6210\u30FB\u53D6\u5F97\u30FB\u524A\u9664\uFF09\u3067\u5B9F\u884C\u3067\u304D\u307E\u3059\uFF08\u8A08\u753B\u540D `KORDER_CURSOR`\uFF09\u3002\r\n\r\n\u30AB\u30FC\u30BD\u30EB\u3092\u5229\u7528\u3059\u308B\u6761\u4EF6\uFF08\u3059\u3079\u3066\u6E80\u305F\u3059\u5834\u5408\u3060\u3051\uFF09:\r\n\r\n- \u4E0A\u8A18\u306E `KORDER BY` \u5171\u901A\u6761\u4EF6\uFF08\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB SELECT\u30FB\u5358\u4E00\u7269\u7406\u30A2\u30D7\u30EA\u30FB\u975E\u4FEE\u98FE\u30AD\u30FC\u30FB\u578B allowlist\u30FBWHERE \u5B8C\u5168\u62BC\u3057\u4E0B\u3052\u30FB`KLIKE` \u306A\u3057\u30FB`LIMIT` \u660E\u793A\uFF09\u3092\u3059\u3079\u3066\u6E80\u305F\u3059\r\n- \u5358\u767AGET\u306E\u7A93\uFF08`LIMIT \u2264 500` \u304B\u3064 `OFFSET \u2264 10000` \u304B\u3064 `LIMIT \u2264 maxRecords`\uFF09\u306B**\u53CE\u307E\u3089\u306A\u3044**\u3002\u53CE\u307E\u308B\u5834\u5408\u306F\u5F93\u6765\u3069\u304A\u308A\u5358\u767AGET\uFF08`KORDER_NATIVE`\uFF09\u3092\u512A\u5148\u3059\u308B\r\n- **\u8D70\u67FB\u4EF6\u6570 `OFFSET + LIMIT` \u304C\u5B9F\u884C\u6642 `maxRecords` \u4EE5\u4E0B**\u3002\u30AB\u30FC\u30BD\u30EB\u3067\u306F OFFSET \u5206\u3092 kSQL \u304C\u5148\u982D\u304B\u3089\u53D7\u4FE1\u3057\u3066\u8AAD\u307F\u6368\u3066\u308B\u305F\u3081\u3001\u8FD4\u5374\u884C\u6570\u3067\u306F\u306A\u304F\u8D70\u67FB\u4EF6\u6570\u306B `maxRecords` \u304C\u639B\u304B\u308A\u307E\u3059\uFF08\u5358\u767AGET\u306E OFFSET \u306F\u30B5\u30FC\u30D0\u30FC\u304C\u8AAD\u307F\u98DB\u3070\u3059\u305F\u3081\u5BFE\u8C61\u5916 \u2014 \u3053\u306E\u975E\u5BFE\u79F0\u306F\u300CkSQL \u304C\u53D7\u4FE1\u3059\u308B\u884C\u6570\u306E\u4E0A\u9650\u300D\u3068\u3044\u3046 `maxRecords` \u306E\u610F\u5473\u305D\u306E\u3082\u306E\u3067\u3059\uFF09\r\n- \u6761\u4EF6\u3092\u6E80\u305F\u3055\u306A\u3044\u5834\u5408\u306F planning error\u3002\u901A\u5E38 `ORDER BY` \u3078\u9ED9\u3063\u3066\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u305B\u3093\r\n\r\n```sql\r\n-- v3.1.0: 10,001 \u4EF6\u3092 kintone \u56FA\u6709\u9806\u306E\u307E\u307E\u53D6\u5F97\r\nSELECT \u4F1A\u793E\u540D, \u91D1\u984D\r\nFROM APP100\r\nKORDER BY \u91D1\u984D DESC, $id ASC\r\nLIMIT 10001\r\n-- CLI/MCP \u306E\u65E2\u5B9A maxRecords=500 \u3067\u306F\u8D70\u67FB\u4EF6\u6570\u304C\u8D85\u904E\u3059\u308B\u305F\u3081\u3001\r\n-- --max-records 10001 \u7B49\u3078\u660E\u793A\u7684\u306B\u5F15\u304D\u4E0A\u3052\u308B\r\n```\r\n\r\n> **\u30AB\u30FC\u30BD\u30EB\u306E\u7279\u9577\u30FB\u5236\u9650\uFF08\u6CE8\u91C8\uFF09:**\r\n>\r\n> - **\u5BFE\u8C61\u96C6\u5408\u306F\u30AB\u30FC\u30BD\u30EB\u4F5C\u6210\u6642\u70B9\u3067\u56FA\u5B9A\u3001\u5024\u306F\u5404\u53D6\u5F97\u6642\u70B9** \u2014 \u5B8C\u5168\u306A\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u8D70\u67FB\u4E2D\u306B\u30EC\u30B3\u30FC\u30C9\u304C\u66F4\u65B0\u3055\u308C\u308B\u3068\u3001\u8FD4\u308B\u5024\u306F\u53D6\u5F97\u6642\u70B9\u306E\u3082\u306E\u306B\u306A\u308A\u3001\u30BD\u30FC\u30C8\u30AD\u30FC\u81EA\u4F53\u304C\u66F4\u65B0\u3055\u308C\u305F\u5834\u5408\u306F\u7D50\u679C\u304C\u8868\u793A\u5024\u4E0A KORDER \u9806\u306B\u898B\u3048\u306A\u3044\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002\u66F4\u65B0\u306E\u306A\u3044\u6642\u9593\u5E2F\u306E\u5B9F\u884C\u3092\u63A8\u5968\u3057\u307E\u3059\r\n> - **\u30AB\u30FC\u30BD\u30EB\u306F 1 \u30C9\u30E1\u30A4\u30F3\u6700\u5927 10 \u500B**\u3092\u3001kSQL \u4EE5\u5916\u306E\u88FD\u54C1\u30FB\u4ED6\u30D7\u30ED\u30BB\u30B9\u3082\u542B\u3081\u3066\u5171\u6709\u3057\u307E\u3059\u3002kSQL \u306F\u81EA\u5236\u306E\u305F\u3081\u540C\u6642\u30AB\u30FC\u30BD\u30EB\u3092\u65E2\u5B9A 2\u30FB\u6700\u5927 5 \u306B\u5236\u9650\u3057\u307E\u3059\u3002\u30C9\u30E1\u30A4\u30F3\u5168\u4F53\u306E\u7A7A\u304D\u67A0\u306F\u4FDD\u8A3C\u3067\u304D\u306A\u3044\u305F\u3081\u3001\u5185\u90E8\u4E0A\u9650\u4EE5\u4E0B\u3067\u3082\u4F5C\u6210\u304C\u5931\u6557\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059\r\n> - **\u6709\u52B9\u671F\u9650\u306F\u4F5C\u6210\u304B\u3089 10 \u5206**\uFF08\u6B8B\u4EF6\u53D6\u5F97\u3067\u5EF6\u9577\uFF09\u3002\u5168\u4EF6\u53D6\u5F97\u307E\u305F\u306F\u660E\u793A\u524A\u9664\u3067\u89E3\u653E\u3055\u308C\u307E\u3059\u3002kSQL \u306F\u5FC5\u8981\u306A\u7A93\u3078\u5230\u9054\u3057\u305F\u6642\u70B9\u3067\u30AB\u30FC\u30BD\u30EB\u3092\u5373\u6642\u524A\u9664\u3057\u307E\u3059\u304C\u3001\u7570\u5E38\u7D42\u4E86\u6642\u306F\u6700\u5927 10 \u5206\u7A0B\u5EA6\u3001\u30C9\u30E1\u30A4\u30F3\u306E\u67A0\u3092 1 \u3064\u5360\u6709\u3059\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\r\n> - **\u53D6\u5F97\u306F 500 \u4EF6\u305A\u3064**\u306E\u9010\u6B21\u30DA\u30FC\u30B8\u3067\u3001kintone \u304C\u8FD4\u3057\u305F\u9806\u5E8F\u3092\u305D\u306E\u307E\u307E\u7D50\u679C\u306B\u3057\u307E\u3059\uFF08\u30ED\u30FC\u30AB\u30EB\u518D\u30BD\u30FC\u30C8\u30FB`$id` \u306E\u81EA\u52D5\u8FFD\u88DC\u306A\u3057\uFF09\u3002\u540C\u5024\u7FA4\u306E\u6C7A\u5B9A\u6027\u304C\u5FC5\u8981\u306A\u3089\u5358\u767AGET\u3068\u540C\u69D8\u306B `$id` \u3092\u6700\u5F8C\u306E\u30AD\u30FC\u3078\u660E\u793A\u3057\u3066\u304F\u3060\u3055\u3044\r\n> - **\u30AB\u30FC\u30BD\u30EB\u306E\u4F5C\u6210\u30FB\u53D6\u5F97\u306F\u81EA\u52D5\u518D\u8A66\u884C\u3057\u307E\u305B\u3093**\u3002\u5FDC\u7B54\u55AA\u5931\u6642\u306B\u518D\u8A66\u884C\u3059\u308B\u3068\u3001\u5B64\u5150\u30AB\u30FC\u30BD\u30EB\uFF08\u4F5C\u6210\uFF09\u3084\u30DA\u30FC\u30B8\u6B20\u843D\uFF08\u53D6\u5F97\uFF09\u304C\u8D77\u304D\u5F97\u308B\u305F\u3081\u3067\u3059\u3002\u4F5C\u6210\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u6642\u306F\u30AF\u30A8\u30EA\u306E\u7D5E\u308A\u8FBC\u307F\u30FB\u5358\u7D14\u5316\u3092\u6848\u5185\u3059\u308B\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\r\n\r\n\u540C\u6642\u30AB\u30FC\u30BD\u30EB\u4E0A\u9650\u306FCLI\u306E`--cursor-max-active`\u3001\u74B0\u5883\u5909\u6570`KSQL_CURSOR_MAX_ACTIVE`\u3001profile\u306E`query.cursorMaxActive`\u3001MCP\u5165\u529B`cursorMaxActive`\u3001plugin\u306E\u53D6\u5F97\u30AA\u30D7\u30B7\u30E7\u30F3\u30671..5\u3078\u8A2D\u5B9A\u3067\u304D\u307E\u3059\u3002\u65E2\u5B9A\u306F2\u3067\u3059\u3002\u540C\u4E00process\u30FB\u540C\u4E00host\u3067\u5F8C\u304B\u3089\u5909\u66F4\u3057\u305F\u5834\u5408\u3082\u6B21\u306E\u53D6\u5F97\u304B\u3089\u53CD\u6620\u3055\u308C\u307E\u3059\u3002\u4E0A\u9650\u3092\u4E0B\u3052\u3066\u3082\u65E2\u5B58Cursor\u306F\u5F37\u5236\u7D42\u4E86\u305B\u305A\u3001active\u6570\u304C\u65B0\u4E0A\u9650\u3092\u4E0B\u56DE\u308B\u307E\u3067\u65B0\u898F\u4F5C\u6210\u3092\u5F85\u6A5F\u3055\u305B\u307E\u3059\u3002\r\n\r\n`KORDER`\u306F\u4E88\u7D04\u8A9E\u3067\u3059\u3002\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F`` `KORDER` ``\u3068\u8A18\u8FF0\u3057\u307E\u3059\u3002\r\n\r\n\r\n\r\n---\r\n\r\n## 10.1 \u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570\r\n\r\n\u9806\u4F4D\u4ED8\u3051\u3068\u30B0\u30EB\u30FC\u30D7\u5185\u9023\u756A\u306B\u3001\u6B21\u306E3\u95A2\u6570\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570\u3092\u542B\u3080SELECT\u306F\u5168\u4EF6\u3092\u53D6\u5F97\u3057\u3066JS\u3067\u8A55\u4FA1\u3059\u308B\u305F\u3081\u3001\u5E38\u306BFULL_SCAN\u30E2\u30FC\u30C9\u3067\u3059\u3002\r\n\r\n```sql\r\nROW_NUMBER() OVER ([PARTITION BY \u30D5\u30A3\u30FC\u30EB\u30C9 [, ...]] [ORDER BY \u30AD\u30FC [ASC|DESC] [, ...]]) AS alias\r\nRANK() OVER ([PARTITION BY \u30D5\u30A3\u30FC\u30EB\u30C9 [, ...]] [ORDER BY \u30AD\u30FC [ASC|DESC] [, ...]]) AS alias\r\nDENSE_RANK() OVER ([PARTITION BY \u30D5\u30A3\u30FC\u30EB\u30C9 [, ...]] [ORDER BY \u30AD\u30FC [ASC|DESC] [, ...]]) AS alias\r\n```\r\n\r\n- `ROW_NUMBER` \u2014 \u540C\u9806\u4F4D\u3092\u4F5C\u3089\u305A\u30011\u304B\u3089\u9023\u756A\u3092\u4ED8\u3051\u308B\r\n- `RANK` \u2014 \u540C\u5024\u306F\u540C\u9806\u4F4D\u3002\u6B21\u306E\u9806\u4F4D\u3092\u98DB\u3070\u3059\uFF08`1, 1, 3`\uFF09\r\n- `DENSE_RANK` \u2014 \u540C\u5024\u306F\u540C\u9806\u4F4D\u3002\u6B21\u306E\u9806\u4F4D\u3092\u98DB\u3070\u3055\u306A\u3044\uFF08`1, 1, 2`\uFF09\r\n- `PARTITION BY` \u7701\u7565\u6642\u306F\u5168\u884C\u30921\u30B0\u30EB\u30FC\u30D7\u3068\u3057\u3066\u6271\u3046\r\n- `ORDER BY` \u7701\u7565\u6642\u3001`RANK` / `DENSE_RANK` \u306F\u5168\u884C1\u3002`ROW_NUMBER` \u306F\u53D6\u5F97\u9806\u3067\u63A1\u756A\u3059\u308B\r\n- `AS alias` \u306F\u5FC5\u9808\u3002\u5F15\u6570\u3001\u30D5\u30EC\u30FC\u30E0\u53E5\u3001\u96C6\u8A08\u95A2\u6570\u306E `OVER` \u306F\u672A\u5BFE\u5FDC\r\n\r\n```sql\r\n-- \u9867\u5BA2\u3054\u3068\u306E\u53D7\u6CE8\u3092\u65B0\u3057\u3044\u9806\u306B\u63A1\u756A\r\nSELECT \u9867\u5BA2ID, \u53D7\u6CE8\u65E5, \u91D1\u984D,\r\n ROW_NUMBER() OVER (PARTITION BY \u9867\u5BA2ID ORDER BY \u53D7\u6CE8\u65E5 DESC) AS rn\r\nFROM APP300\r\n```\r\n\r\n`WHERE` \u306F\u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570\u3088\u308A\u5148\u306B\u8A55\u4FA1\u3055\u308C\u308B\u305F\u3081\u3001\u540C\u3058SELECT\u306E `WHERE rn = 1` \u3067\u306F\u7D5E\u308A\u8FBC\u3081\u307E\u305B\u3093\u3002CTE\u3067\u30B9\u30B3\u30FC\u30D7\u3092\u5206\u3051\u308B\u3068\u3001\u5404\u9867\u5BA2\u306E\u6700\u65B0\u884C\u3092\u5168\u5217\u4ED8\u304D\u30671\u6587\u53D6\u5F97\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nWITH ranked AS (\r\n SELECT \u9867\u5BA2ID, \u53D7\u6CE8\u65E5, \u91D1\u984D,\r\n ROW_NUMBER() OVER (PARTITION BY \u9867\u5BA2ID ORDER BY \u53D7\u6CE8\u65E5 DESC) AS rn\r\n FROM APP300\r\n)\r\nSELECT \u9867\u5BA2ID, \u53D7\u6CE8\u65E5, \u91D1\u984D\r\nFROM ranked\r\nWHERE rn = 1\r\n```\r\n\r\n\u30A6\u30A3\u30F3\u30C9\u30A6\u5185\u306E `ORDER BY` \u306F\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E\u901A\u5E38`ORDER BY`\u3068\u540C\u3058canonical\u6BD4\u8F03\u898F\u5247\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002CTE\uFF0F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u7531\u6765\u3067\u3082\u4F1D\u64AD\u3057\u305F\u578B\u30E1\u30BF\u30C7\u30FC\u30BF\u3092\u4F7F\u3044\u3001\u578B\u3092\u78BA\u5B9A\u3067\u304D\u306A\u3044\u5217\u306F\u6587\u5B57\u5217\u3068\u3057\u3066\u6271\u3044\u307E\u3059\u3002\u5024\u306E\u898B\u305F\u76EE\u306B\u3088\u308B\u6570\u5024\uFF0F\u6587\u5B57\u5217\u306E\u30DA\u30A2\u5358\u4F4D\u5207\u66FF\u306F\u884C\u3044\u307E\u305B\u3093\u3002`KORDER BY`\u306F\u30A6\u30A3\u30F3\u30C9\u30A6\u5185\u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\r\n\r\n\u540C\u3058SELECT\u5185\u3067\u306E `GROUP BY`\uFF0F\u96C6\u8A08\u95A2\u6570\u3068\u306E\u4F75\u7528\u306F\u672A\u5BFE\u5FDC\u3067\u3059\u3002\u96C6\u7D04\u7D50\u679C\u3078\u9806\u4F4D\u3092\u4ED8\u3051\u308B\u5834\u5408\u306FCTE\u3067\u30B9\u30B3\u30FC\u30D7\u3092\u5206\u3051\u307E\u3059\u3002\r\n\r\n```sql\r\nWITH agg AS (\r\n SELECT \u90E8\u7F72, SUM(\u58F2\u4E0A) AS \u5408\u8A08 FROM APP300 GROUP BY \u90E8\u7F72\r\n)\r\nSELECT \u90E8\u7F72, \u5408\u8A08, RANK() OVER (ORDER BY \u5408\u8A08 DESC) AS \u9806\u4F4D\r\nFROM agg\r\n```\r\n\r\n---', uri: "ksql://language-reference/10-order-by" }, "11-limit-offset": { heading: "11. LIMIT / OFFSET", text: "## 11. LIMIT / OFFSET\r\n\r\n\u53D6\u5F97\u4EF6\u6570\u306E\u4E0A\u9650\u3068\u30B9\u30AD\u30C3\u30D7\u4EF6\u6570\u3092\u6307\u5B9A\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT * FROM APP100 LIMIT 10\r\nSELECT * FROM APP100 ORDER BY \u4F5C\u6210\u65E5\u6642 DESC LIMIT 50\r\nSELECT * FROM APP100 ORDER BY \u4F5C\u6210\u65E5\u6642 DESC LIMIT 20 OFFSET 40\r\n```\r\n\r\n- `LIMIT n` \u2014 \u6700\u5927 n \u4EF6\u3092\u8FD4\u3059\r\n- `OFFSET m` \u2014 \u5148\u982D m \u4EF6\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3066\u304B\u3089\u8FD4\u3059\uFF08\u30DA\u30FC\u30B8\u30F3\u30B0\u7528\uFF09\r\n\r\n### v3.0.0 \u5236\u9650\u5024\u4E00\u89A7\r\n\r\n| \u5BFE\u8C61 | \u5236\u9650\u5024 | \u8D85\u904E\u30FB\u6761\u4EF6\u4E0D\u6210\u7ACB\u6642\u306E\u52D5\u4F5C |\r\n|---|---:|---|\r\n| \u901A\u5E38`ORDER BY`\u306E`LIMIT` | SQL\u69CB\u6587\u4E0A\u306E\u56FA\u5B9A\u4E0A\u9650\u306A\u3057 | REST top-N\u306E\u6761\u4EF6\u3092\u6E80\u305F\u3055\u306A\u3044\u5024\uFF08\u521D\u671F\u7248\u3067\u306F`LIMIT > 500`\u7B49\uFF09\u306F\u7981\u6B62\u305B\u305A\u3001\u5B8C\u5168\u5019\u88DC\u53D6\u5F97\u5F8C\u306Elocal sort\u3078\u5207\u308A\u66FF\u3048\u308B |\r\n| \u901A\u5E38`ORDER BY`\u306E`OFFSET` | SQL\u69CB\u6587\u4E0A\u306E\u56FA\u5B9A\u4E0A\u9650\u306A\u3057 | REST top-N\u306E\u6761\u4EF6\u3092\u6E80\u305F\u3055\u306A\u3044\u5024\uFF08\u521D\u671F\u7248\u3067\u306F`OFFSET > 10000`\u7B49\uFF09\u306F\u7981\u6B62\u305B\u305A\u3001local\u8A55\u4FA1\u3078\u5207\u308A\u66FF\u3048\u308B |\r\n| local `ORDER BY`\u306E\u5019\u88DC\u53D6\u5F97 | \u5B9F\u884C\u6642`maxRecords`\u672A\u6E80\u3067\u5B8C\u4E86\u3059\u308B\u3053\u3068 | \u4E0A\u9650\u3078\u5230\u9054\u3059\u308B\u3068\u3001`LIMIT 1`\u3084`onLimit=truncate`\u3067\u3082`FetchAllLimitError`\u3002\u90E8\u5206\u5019\u88DC\u306Etop-N\u306F\u8FD4\u3055\u306A\u3044 |\r\n| `CANONICAL_REST_TOP_N`\u306E\u7A93 | `LIMIT 0..500`\u304B\u3064`LIMIT <= maxRecords`\u3001`OFFSET 0..10000` | \u5229\u7528\u8005\u30A8\u30E9\u30FC\u306B\u306F\u305B\u305A`CANONICAL_LOCAL`\u3078\u5207\u308A\u66FF\u3048\u308B\u3002\u521D\u671F\u30AD\u30FCallowlist\u306F`$id`\u306E\u307F |\r\n| `KORDER BY`\u306E`LIMIT` | **\u5FC5\u9808**\u3002`0..500`\u304B\u3064`LIMIT <= maxRecords` | planning error\u3002\u901A\u5E38`ORDER BY`\u3078\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u306A\u3044 |\r\n| `KORDER BY`\u306E`OFFSET` | \u7701\u7565\u307E\u305F\u306F`0..10000` | `10001`\u4EE5\u4E0A\u306Fplanning error\u3002API\u304C\u53D7\u7406\u3059\u308B\u5834\u5408\u3067\u3082\u8A31\u53EF\u3057\u306A\u3044 |\r\n\r\n`KORDER BY` \u306E\u7A93\u5236\u9650\u306F **v3.1.0** \u3067\u7DE9\u548C\u3055\u308C\u3001\u5358\u767AGET\u306B\u53CE\u307E\u3089\u306A\u3044\u7A93\u3092 Cursor API \u3067\u5B9F\u884C\u3067\u304D\u307E\u3059\uFF08\u6761\u4EF6: \u8D70\u67FB\u4EF6\u6570 `OFFSET + LIMIT` \u2264 `maxRecords`\uFF09\u3002\u8A73\u7D30\u3068\u6CE8\u610F\u70B9\u306F \xA710\u300C\u5927\u304D\u3044\u7A93\u3068 Cursor API\u300D\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n`maxRecords`\u306FSQL\u306E\u8FD4\u5374\u884C\u6570\u3067\u306F\u306A\u304F\u3001REST\u304B\u3089\u53D6\u5F97\u3057\u3066\u4FDD\u6301\u3059\u308B\u5019\u88DC\u884C\u6570\u306E\u4E0A\u9650\u3067\u3059\u3002\u5165\u53E3\u3054\u3068\u306E\u65E2\u5B9A\u5024\u306F\u6B21\u306E\u3068\u304A\u308A\u3067\u3059\u3002\r\n\r\n| \u5B9F\u884C\u9762 | `maxRecords`\u65E2\u5B9A\u5024 | \u5909\u66F4\u65B9\u6CD5 |\r\n|---|---:|---|\r\n| \u30A8\u30F3\u30B8\u30F3API\u3092\u76F4\u63A5\u5229\u7528 | 10,000\u4EF6 | `ExecuteOptions.maxRecords` |\r\n| CLI | 500\u4EF6 | `--max-records`\uFF0F`KSQL_MAX_RECORDS`\uFF0Fprofile `query.maxRecords` |\r\n| MCP | 500\u4EF6 | `ksql_query`\u30FB`ksql_explain`\u7B49\u306Etool\u5165\u529B`maxRecords`\uFF0F`KSQL_MAX_RECORDS`\uFF0Fprofile `query.maxRecords` |\r\n| \u30D7\u30E9\u30B0\u30A4\u30F3 | 3,000\u4EF6 | \u5B9F\u884C\u753B\u9762\u306E\u300C\u6700\u5927\u53D6\u5F97\u4EF6\u6570\u300D |\r\n\r\n\u5024\u3092\u5F15\u304D\u4E0A\u3052\u308B\u3068API\u547C\u51FA\u3057\u56DE\u6570\u3001\u30E1\u30E2\u30EA\u4F7F\u7528\u91CF\u3001\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u30EA\u30B9\u30AF\u3082\u5897\u3048\u307E\u3059\u3002`CREATE TEMP TABLE`\u306E\u5B9F\u4F53\u5316\u306B\u306F\u5225\u306E`tempTableMaxRows`\uFF08\u65E2\u5B9A10,000\u4EF6\uFF09\u304C\u9069\u7528\u3055\u308C\u3001`maxRecords`\u3068\u306F\u72EC\u7ACB\u3067\u3059\u3002\r\n\r\n> **`LIMIT`\u3068`maxRecords`\u306F\u5225\u306E\u5024\u3067\u3059:** `LIMIT`\u306F\u8FD4\u5374\u884C\u6570\u3001`maxRecords`\u306F\u5019\u88DC\u53D6\u5F97\u6570\u3092\u5236\u5FA1\u3057\u307E\u3059\u3002`LIMIT`\u3092\u7701\u7565\u3057\u3066\u3082\u7121\u5236\u9650\u306B\u306F\u306A\u3089\u305A\u3001\u4E0A\u8868\u306E\u5165\u53E3\u5225`maxRecords`\u304C\u9069\u7528\u3055\u308C\u307E\u3059\u3002\r\n\r\n> **`LIMIT > 500` \u306E\u65E9\u671F\u505C\u6B62:** `ORDER BY`\u304C\u306A\u304FKLIKE\u3092\u542B\u307E\u306A\u3044\u5B89\u5168\u306A\u7D4C\u8DEF\u3067\u306F\u3001`OFFSET + LIMIT`\u4EF6\u3092\u53D6\u5F97\u3057\u305F\u6642\u70B9\u3067\u6B63\u5E38\u7D42\u4E86\u3057\u307E\u3059\u3002`maxRecords`\u306F\u5B9F\u969B\u306B\u53D6\u5F97\u3059\u308B\u884C\u6570\u306E\u4E0A\u9650\u3067\u3059\u3002\r\n\r\n> **ORDER BY\u3068\u53D6\u5F97\u4E0A\u9650\uFF08v3.0.0\uFF09:** \u30ED\u30FC\u30AB\u30EB`ORDER BY`\u306F\u6B63\u3057\u3044top-N\u306E\u305F\u3081\u5B8C\u5168\u306A\u5019\u88DC\u96C6\u5408\u3092\u5FC5\u8981\u3068\u3057\u307E\u3059\u3002\u4E0A\u9650\u5230\u9054\u6642\u306B`onLimit=truncate`\u3067\u90E8\u5206\u5019\u88DC\u3092\u4E26\u3079\u66FF\u3048\u3066\u8FD4\u3055\u305A\u3001\u30A8\u30E9\u30FC\u306B\u3057\u307E\u3059\u3002`CANONICAL_REST_TOP_N`\uFF08\u521D\u671Fallowlist\u306F`$id`\u306E\u307F\uFF09\u3068`KORDER_NATIVE`\u306F\u5358\u767AREST\u7A93\u306A\u306E\u3067\u3001\u3053\u306E\u5B8C\u5168\u5165\u529B\u30A8\u30E9\u30FC\u306E\u5BFE\u8C61\u5916\u3067\u3059\u3002\r\n\r\n> **SIMPLE \u30E2\u30FC\u30C9\uFF08JOIN \u306A\u3057\uFF09:** `ORDER BY`\u306EREST\u62BC\u3057\u4E0B\u3052\u306FLIMIT\u5024\u3060\u3051\u3067\u6C7A\u3081\u305A\u3001schema-aware planner\u304CWHERE\u30FB\u578B\u30FBquery\u5F62\u72B6\u30FB\u7A93\u5168\u4F53\u3092\u691C\u67FB\u3057\u307E\u3059\u3002\u305D\u308C\u4EE5\u5916\u306F\u5168\u5019\u88DC\u53D6\u5F97\u5F8C\u306Bcanonical\u9806\u3092\u9069\u7528\u3057\u307E\u3059\u3002\r\n> **FULL_SCAN \u30E2\u30FC\u30C9\uFF08JOIN \u3042\u308A\u7B49\uFF09:** JS \u5074\u3067\u30B9\u30E9\u30A4\u30B9\u51E6\u7406\u3057\u307E\u3059\u3002\r\n\r\n---", uri: "ksql://language-reference/11-limit-offset" }, "12-union": { heading: "12. UNION / UNION ALL", text: "## 12. UNION / UNION ALL\r\n\r\n\u8907\u6570\u306E SELECT \u7D50\u679C\u3092\u7E26\u306B\u7D50\u5408\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSELECT \u30AB\u30E9\u30E0\u30EA\u30B9\u30C8 FROM \u30C6\u30FC\u30D6\u30EB1\r\nUNION [ALL]\r\nSELECT \u30AB\u30E9\u30E0\u30EA\u30B9\u30C8 FROM \u30C6\u30FC\u30D6\u30EB2\r\n```\r\n\r\n- `UNION` \u2014 \u91CD\u8907\u884C\u3092\u9664\u53BB\uFF08DISTINCT\uFF09\r\n- `UNION ALL` \u2014 \u91CD\u8907\u884C\u3092\u305D\u306E\u307E\u307E\u4FDD\u6301\uFF08\u9AD8\u901F\uFF09\r\n- \u4E21\u8FBA\u306E\u5217\u6570\u304C\u4E00\u81F4\u3057\u306A\u3044\u5834\u5408\u306F\u30A8\u30E9\u30FC\r\n- \u53F3\u8FBA\u306E\u5217\u540D\u306F\u5DE6\u8FBA\u306E\u5217\u540D\u306B\u4F4D\u7F6E\u5BFE\u5FDC\u3067\u30EA\u30DE\u30C3\u30D7\u3055\u308C\u307E\u3059\r\n\r\n```sql\r\n-- 2\u30A2\u30D7\u30EA\u306E\u30C7\u30FC\u30BF\u3092\u91CD\u8907\u9664\u53BB\u3057\u3066\u7D50\u5408\r\nSELECT \u9867\u5BA2\u540D, \u91D1\u984D FROM APP100\r\nUNION\r\nSELECT \u9867\u5BA2\u540D, \u91D1\u984D FROM APP200\r\n\r\n-- \u91CD\u8907\u3092\u4FDD\u6301\u3057\u3066\u5168\u4EF6\u7D50\u5408\r\nSELECT \u9867\u5BA2\u540D FROM APP100\r\nUNION ALL\r\nSELECT \u9867\u5BA2\u540D FROM APP200\r\n\r\n-- 3\u3064\u4EE5\u4E0A\u306E\u9023\u9396\uFF08\u5DE6\u7D50\u5408\uFF09\r\nSELECT \u540D\u524D FROM APP100\r\nUNION\r\nSELECT \u540D\u524D FROM APP200\r\nUNION\r\nSELECT \u540D\u524D FROM APP300\r\n```\r\n\r\n> UNION \u306F\u5E38\u306B FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\u3002\r\n\r\n---", uri: "ksql://language-reference/12-union" }, "13-with-cte": { heading: "13. WITH \u53E5\uFF08CTE\uFF09", text: "## 13. WITH \u53E5\uFF08CTE\uFF09\r\n\r\n\u30AF\u30A8\u30EA\u306E\u5192\u982D\u3067\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\uFF08CTE: Common Table Expression\uFF09\u3092\u5B9A\u7FA9\u3057\u3001\u5F8C\u7D9A\u306E SELECT / JOIN \u3067\u53C2\u7167\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nWITH CTE\u540D AS (\r\n \u30B5\u30D6\u30AF\u30A8\u30EA\r\n)\r\nSELECT ...\r\nFROM CTE\u540D\r\n```\r\n\r\n### \u57FA\u672C\u4F8B\r\n\r\n```sql\r\n-- GROUP BY \u96C6\u8A08\u7D50\u679C\u3092 CTE \u306B\u5165\u308C\u3066\u4E0A\u4F4D N \u4EF6\u3092\u53D6\u5F97\r\nWITH \u6708\u5225\u96C6\u8A08 AS (\r\n SELECT \u6708, SUM(\u91D1\u984D) AS \u5408\u8A08\r\n FROM APP100\r\n GROUP BY \u6708\r\n)\r\nSELECT \u6708, \u5408\u8A08\r\nFROM \u6708\u5225\u96C6\u8A08\r\nORDER BY \u5408\u8A08 DESC\r\nLIMIT 5\r\n```\r\n\r\n### CTE \u3092 JOIN \u3067\u4F7F\u3046\r\n\r\n```sql\r\nWITH \u53D7\u6CE8\u96C6\u8A08 AS (\r\n SELECT \u9867\u5BA2ID, SUM(\u91D1\u984D) AS \u5408\u8A08\r\n FROM APP100\r\n GROUP BY \u9867\u5BA2ID\r\n)\r\nSELECT c.\u9867\u5BA2\u540D, r.\u5408\u8A08\r\nFROM APP200 AS c\r\nINNER JOIN \u53D7\u6CE8\u96C6\u8A08 AS r ON c.\u9867\u5BA2ID = r.\u9867\u5BA2ID\r\nWHERE r.\u5408\u8A08 > 100000\r\n```\r\n\r\n### \u8907\u6570 CTE\r\n\r\n```sql\r\nWITH\r\n A\u985E AS (SELECT \u7A2E\u5225, SUM(\u91D1\u984D) AS \u5408\u8A08 FROM APP100 WHERE \u7A2E\u5225 = 'A' GROUP BY \u7A2E\u5225),\r\n B\u985E AS (SELECT \u7A2E\u5225, SUM(\u91D1\u984D) AS \u5408\u8A08 FROM APP100 WHERE \u7A2E\u5225 = 'B' GROUP BY \u7A2E\u5225)\r\nSELECT \u7A2E\u5225, \u5408\u8A08 FROM A\u985E\r\nUNION ALL\r\nSELECT \u7A2E\u5225, \u5408\u8A08 FROM B\u985E\r\n```\r\n\r\n### CTE \u5185\u3067 UNION\r\n\r\n```sql\r\nWITH \u7D71\u5408 AS (\r\n SELECT \u9867\u5BA2\u540D FROM APP100\r\n UNION ALL\r\n SELECT \u9867\u5BA2\u540D FROM APP200\r\n)\r\nSELECT \u9867\u5BA2\u540D FROM \u7D71\u5408\r\nWHERE \u9867\u5BA2\u540D LIKE '\u7530%'\r\n```\r\n\r\n### CTE \u30A4\u30F3\u30E9\u30A4\u30F3\u5316\uFF08\u81EA\u52D5\u6700\u9069\u5316\uFF09\r\n\r\n\u5358\u7D14\u306A CTE\uFF08GROUP BY\u30FB\u96C6\u8A08\u30FBJOIN \u306A\u3057\uFF09\u306F\u81EA\u52D5\u7684\u306B\u30A4\u30F3\u30E9\u30A4\u30F3\u5316\u3055\u308C\u3001CTE \u306E WHERE \u3068\u6700\u7D42\u30AF\u30A8\u30EA\u306E WHERE \u304C\u5408\u6210\u3055\u308C\u3066 kintone REST API \u306B\u9001\u3089\u308C\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u66F8\u3044\u305F\u30AF\u30A8\u30EA\r\nWITH \u5BFE\u8C61 AS (SELECT * FROM APP100 WHERE \u533A\u5206 = 'A')\r\nSELECT * FROM \u5BFE\u8C61 WHERE \u91D1\u984D > 1000\r\n\r\n-- \u5B9F\u884C\u3055\u308C\u308B\u30AF\u30A8\u30EA\uFF08\u30A4\u30F3\u30E9\u30A4\u30F3\u5316\uFF09\r\n-- kintone \u30AF\u30A8\u30EA: \u533A\u5206 = \"A\" and \u91D1\u984D > 1000\r\n```\r\n\r\n\u30A4\u30F3\u30E9\u30A4\u30F3\u5316\u3055\u308C\u306A\u3044\u5834\u5408\uFF08FULL_SCAN \u306E\u307E\u307E\uFF09:\r\n- CTE \u304C\u8907\u6570\u3042\u308B\r\n- CTE \u672C\u4F53\u306B GROUP BY / \u96C6\u8A08\u95A2\u6570\u304C\u3042\u308B\r\n- \u6700\u7D42\u30AF\u30A8\u30EA\u3067 CTE \u3092 JOIN \u3057\u3066\u3044\u308B\r\n\r\n### CTE \u5185\u3067\u306E SHOW APPS / DESCRIBE\r\n\r\n`SHOW APPS` \u3068 `DESCRIBE` / `DESC` \u306E\u7D50\u679C\u3082 CTE \u3068\u3057\u3066\u5B9A\u7FA9\u3057\u3001\u5F8C\u7D9A\u30AF\u30A8\u30EA\u3067\u30D5\u30A3\u30EB\u30BF\u30FB\u52A0\u5DE5\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u540D\u524D\u3067\u30A2\u30D7\u30EA\u4E00\u89A7\u3092\u7D5E\u308A\u8FBC\u3080\r\nWITH \u30A2\u30D7\u30EA\u4E00\u89A7 AS (SHOW APPS)\r\nSELECT * FROM \u30A2\u30D7\u30EA\u4E00\u89A7\r\nWHERE name LIKE '\u53D7\u6CE8%'\r\n\r\n-- \u30C6\u30AD\u30B9\u30C8\u7CFB\u30D5\u30A3\u30FC\u30EB\u30C9\u3060\u3051\u62BD\u51FA\r\nWITH \u30D5\u30A3\u30FC\u30EB\u30C9 AS (DESCRIBE APP100)\r\nSELECT * FROM \u30D5\u30A3\u30FC\u30EB\u30C9\r\nWHERE type IN ('SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT')\r\n\r\n-- DESC \u3082\u4F7F\u7528\u53EF\u80FD\r\nWITH \u30D5\u30A3\u30FC\u30EB\u30C9 AS (DESC APP100)\r\nSELECT fieldCode, label FROM \u30D5\u30A3\u30FC\u30EB\u30C9\r\nORDER BY fieldCode ASC\r\n```\r\n\r\n**\u6CE8\u610F\u4E8B\u9805:**\r\n- CTE \u672C\u4F53\u306E\u30B5\u30D6\u30AF\u30A8\u30EA\u306F SIMPLE / FULL_SCAN \u3092\u81EA\u52D5\u5224\u5B9A\r\n- \u518D\u5E30 CTE \u306F\u975E\u5BFE\u5FDC\r\n\r\n---", uri: "ksql://language-reference/13-with-cte" }, "14-show-apps-describe": { heading: "14. SHOW APPS / DESCRIBE", text: "## 14. SHOW APPS / DESCRIBE\r\n\r\n### SHOW APPS \u2014 \u30A2\u30D7\u30EA\u4E00\u89A7\u53D6\u5F97\r\n\r\nkintone \u4E0A\u306E\u3059\u3079\u3066\u306E\u30A2\u30D7\u30EA\uFF08\u6700\u5927 1,000 \u4EF6\uFF09\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSHOW APPS\r\n```\r\n\r\n| \u30AB\u30E9\u30E0 | \u5185\u5BB9 |\r\n|--------|------|\r\n| `appId` | \u30A2\u30D7\u30EA ID |\r\n| `name` | \u30A2\u30D7\u30EA\u540D |\r\n| `description` | \u8AAC\u660E |\r\n\r\n> 100 \u4EF6\u5358\u4F4D\u3067\u81EA\u52D5\u30DA\u30FC\u30B8\u30F3\u30B0\u3057\u3001\u6700\u5927 1,000 \u4EF6\u307E\u3067\u53D6\u5F97\u3057\u307E\u3059\u3002\r\n\r\n### DESCRIBE / DESC \u2014 \u30D5\u30A3\u30FC\u30EB\u30C9\u4E00\u89A7\u53D6\u5F97\r\n\r\n\u6307\u5B9A\u3057\u305F\u30A2\u30D7\u30EA\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u5B9A\u7FA9\u3092\u53D6\u5F97\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nDESCRIBE APP100\r\nDESC APP100 -- \u7701\u7565\u5F62\uFF08DESCRIBE \u3068\u540C\u7B49\uFF09\r\n```\r\n\r\n| \u30AB\u30E9\u30E0 | \u5185\u5BB9 |\r\n|--------|------|\r\n| `fieldCode` | \u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9 |\r\n| `label` | \u30D5\u30A3\u30FC\u30EB\u30C9\u30E9\u30D9\u30EB |\r\n| `type` | \u30D5\u30A3\u30FC\u30EB\u30C9\u30BF\u30A4\u30D7\uFF08`SINGLE_LINE_TEXT`\u3001`NUMBER` \u7B49\uFF09 |\r\n\r\n```sql\r\n-- WITH \u53E5\u3068\u7D44\u307F\u5408\u308F\u305B\u3066\u30D5\u30A3\u30EB\u30BF\r\nWITH \u30A2\u30D7\u30EA AS (SHOW APPS)\r\nSELECT * FROM \u30A2\u30D7\u30EA WHERE name LIKE '\u53D7\u6CE8%'\r\n\r\nWITH \u30D5\u30A3\u30FC\u30EB\u30C9 AS (DESC APP100)\r\nSELECT * FROM \u30D5\u30A3\u30FC\u30EB\u30C9 WHERE type = 'NUMBER'\r\n```\r\n\r\n---", uri: "ksql://language-reference/14-show-apps-describe" }, "15-insert": { heading: "15. INSERT", text: "## 15. INSERT\r\n\r\n### \u89AA\u30EC\u30B3\u30FC\u30C9 DML \u306E\u5BFE\u8C61\u30D5\u30A3\u30FC\u30EB\u30C9\u691C\u67FB\r\n\r\n\u89AA\u30EC\u30B3\u30FC\u30C9\u3092\u5BFE\u8C61\u3068\u3059\u308B `INSERT` / `UPDATE` / `UPSERT` \u306F\u3001\u66F8\u304D\u8FBC\u307F\u5148\u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u5BFE\u8C61\u30A2\u30D7\u30EA\u306B\u5B58\u5728\u3057\u3001\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306B\u3042\u308A\u3001\u66F8\u304D\u8FBC\u307F\u53EF\u80FD\u3067\u3042\u308B\u3053\u3068\u3092\u5B9F\u884C\u524D\u306B\u691C\u67FB\u3057\u307E\u3059\u3002\u4E0D\u5B58\u5728\u30D5\u30A3\u30FC\u30EB\u30C9\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u306E\u8AA4\u8A18\u3092\u542B\u3080\uFF09\u3068\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u3001\u884C\u5358\u4F4D\u3067\u7121\u8996\u30FB\u9694\u96E2\u305B\u305A\u6587\u5358\u4F4D\u306E `ArgumentError` \u306B\u306A\u308A\u307E\u3059\u3002\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u3092\u66F4\u65B0\u3059\u308B\u5834\u5408\u306F `APP100$\u660E\u7D30` \u306E\u3088\u3046\u306A[\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB DML](#\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB-dml)\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n\u3053\u306E\u691C\u67FB\u306F `VALIDATE ONLY` / `ON ERROR SKIP` \u3092\u542B\u3080\u5168\u7D4C\u8DEF\u3067\u3001\u30BD\u30FC\u30B9 SELECT\u3001\u66F4\u65B0\u30FBUPSERT\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u306E\u53D6\u5F97\u3001\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0\u3001POST / PUT \u3088\u308A\u524D\u306B\u5B8C\u4E86\u3057\u307E\u3059\u3002\u4E0D\u6B63\u306A\u66F8\u304D\u8FBC\u307F\u5148\u3067\u306F\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u306E\u53D6\u5F97\u4EE5\u5916\u306E\u30EC\u30B3\u30FC\u30C9 API \u3084\u78BA\u8A8D\u51E6\u7406\u3092\u547C\u3073\u307E\u305B\u3093\u3002\r\n\r\n### VALUES \u306B\u3088\u308B\u767B\u9332\r\n\r\n```sql\r\nINSERT INTO APP100 (\u30D5\u30A3\u30FC\u30EB\u30C91, \u30D5\u30A3\u30FC\u30EB\u30C92, ...)\r\nVALUES (\u50241, \u50242, ...)\r\n```\r\n\r\nVALUES \u306E\u6570\u5024\u306B\u306F\u5358\u9805\u7B26\u53F7\u4ED8\u304D\u30EA\u30C6\u30E9\u30EB\uFF08`-5` / `+5` / `-0.5` / `+0.5`\uFF09\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\u7B26\u53F7\u306E\u76F4\u5F8C\u306F\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u306B\u9650\u3089\u308C\u3001`--5` / `+-5` / `-+5` / `++5`\u3001\u7B97\u8853\u5F0F\u3001\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3001\u95A2\u6570\u547C\u3073\u51FA\u3057\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002\u5F15\u7528\u7B26\u4ED8\u304D\u306E `'-5'` \u306F\u6570\u5024\u3067\u306F\u306A\u304F\u6587\u5B57\u5217\u3067\u3059\u3002\u3053\u306E\u898F\u5247\u306F\u89AA\u30FB\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306E INSERT VALUES \u3068 UPSERT VALUES \u3067\u5171\u901A\u3067\u3059\u3002\r\n\r\n#### \u5358\u4E00\u30EC\u30B3\u30FC\u30C9\r\n\r\n```sql\r\nINSERT INTO APP100 (\u6C0F\u540D, \u91D1\u984D, \u30B9\u30C6\u30FC\u30BF\u30B9)\r\nVALUES ('\u7530\u4E2D \u592A\u90CE', 50000, '\u9032\u884C\u4E2D')\r\n```\r\n\r\n#### \u8907\u6570\u30EC\u30B3\u30FC\u30C9\uFF08\u4E00\u62EC\u767B\u9332\uFF09\r\n\r\n```sql\r\nINSERT INTO APP100 (\u6C0F\u540D, \u91D1\u984D)\r\nVALUES ('\u7530\u4E2D \u592A\u90CE', 50000),\r\n ('\u9234\u6728 \u82B1\u5B50', 30000),\r\n ('\u4F50\u85E4 \u4E00\u90CE', 80000)\r\n```\r\n\r\n> **\u30D0\u30C3\u30C1\u51E6\u7406:** 100\u4EF6\u3054\u3068\u306B API \u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u5206\u5272\u3057\u3066\u9001\u4FE1\u3057\u307E\u3059\u3002\r\n\r\n> **\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0\uFF08\u30D7\u30E9\u30B0\u30A4\u30F3\uFF09:** `INSERT INTO ... VALUES` \u3082\u5B9F\u884C\u524D\u306B\u767B\u9332\u4EF6\u6570\u3092\u8868\u793A\u3057\u3066\u78BA\u8A8D\u3092\u6C42\u3081\u307E\u3059\u3002 \r\n> \u30AD\u30E3\u30F3\u30BB\u30EB\u3059\u308B\u3068\u767B\u9332\u306F\u884C\u308F\u308C\u307E\u305B\u3093\u3002\r\n\r\n### INSERT INTO ... SELECT\r\n\r\n\u5225\u30A2\u30D7\u30EA\u306E\u30C7\u30FC\u30BF\u3092\u30B3\u30D4\u30FC\u767B\u9332\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nINSERT INTO APP100 (\u30D5\u30A3\u30FC\u30EB\u30C91, \u30D5\u30A3\u30FC\u30EB\u30C92, ...)\r\nSELECT \u52171, \u52172, ...\r\nFROM APP200\r\n[WHERE \u6761\u4EF6]\r\n```\r\n\r\n```sql\r\n-- \u5225\u30A2\u30D7\u30EA\u304B\u3089\u6761\u4EF6\u4ED8\u304D\u3067\u30B3\u30D4\u30FC\r\nINSERT INTO APP100 (\u9867\u5BA2\u540D, \u91D1\u984D)\r\nSELECT \u9867\u5BA2\u540D, \u5408\u8A08\u91D1\u984D\r\nFROM APP200\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u78BA\u5B9A'\r\n\r\n-- \u95A2\u6570\u30FB\u7B97\u8853\u5F0F\u3092\u4F7F\u3063\u3066\u52A0\u5DE5\u3057\u306A\u304C\u3089\u30B3\u30D4\u30FC\r\nINSERT INTO APP100 (\u9867\u5BA2\u540D, \u7A0E\u8FBC\u91D1\u984D)\r\nSELECT UPPER(\u9867\u5BA2\u540D), ROUND(\u91D1\u984D * 1.1)\r\nFROM APP200\r\nWHERE \u91D1\u984D > 0\r\n```\r\n\r\n- SELECT \u306E\u5217\u6570\u3068 INSERT \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u6570\u304C\u4E00\u81F4\u3057\u306A\u3044\u5834\u5408\u306F\u30A8\u30E9\u30FC\r\n- SELECT \u5074\u306F SIMPLE / FULL_SCAN \u81EA\u52D5\u5224\u5B9A\uFF08JOIN\u30FBGROUP BY\u30FB\u95A2\u6570\u3082\u4F7F\u7528\u53EF\uFF09\r\n- \u7D50\u679C\u3092 100 \u4EF6\u30D0\u30C3\u30C1\u3067 POST\r\n\r\n### INSERT \u3067\u306E\u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\r\n\r\n\u30E6\u30FC\u30B6\u30FC\u9078\u629E\u30FB\u7D44\u7E54\u9078\u629E\u30FB\u30B0\u30EB\u30FC\u30D7\u9078\u629E\u30FB\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u30FB\u8907\u6570\u9078\u629E\u30D5\u30A3\u30FC\u30EB\u30C9\u3078\u306E\u66F8\u304D\u8FBC\u307F\u3092\u30B5\u30DD\u30FC\u30C8\u3057\u307E\u3059\u3002 \r\n\u5B9F\u884C\u524D\u306B\u5BFE\u8C61\u30A2\u30D7\u30EA\u306E `getFields()` \u3067\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u3092\u81EA\u52D5\u53D6\u5F97\u3057\u3001\u578B\u306B\u5FDC\u3058\u305F API \u5F62\u5F0F\u306B\u5909\u63DB\u3057\u307E\u3059\u3002\r\n\r\n#### \u30AB\u30F3\u30DE\u533A\u5207\u308A\u6587\u5B57\u5217\uFF08\u901A\u5E38\u30B1\u30FC\u30B9\uFF09\r\n\r\n```sql\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E\uFF08\u5358\u4E00\uFF09\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005) VALUES ('A\u793E', 'user1')\r\n\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E\uFF08\u8907\u6570\uFF09\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005) VALUES ('A\u793E', 'user1,user2')\r\n\r\n-- \u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9 / \u8907\u6570\u9078\u629E\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u30BF\u30B0) VALUES ('A\u793E', '\u91CD\u8981,VIP')\r\n\r\n-- \u7A7A\u306B\u3059\u308B\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005) VALUES ('A\u793E', '')\r\n```\r\n\r\n| SQL \u5024 | \u30D5\u30A3\u30FC\u30EB\u30C9\u578B | kintone API \u9001\u4FE1\u5024 |\r\n|---|---|---|\r\n| `'user1'` | USER_SELECT \u7B49 | `[{\"code\":\"user1\"}]` |\r\n| `'user1,user2'` | USER_SELECT \u7B49 | `[{\"code\":\"user1\"},{\"code\":\"user2\"}]` |\r\n| `'\u9078\u629E\u80A2A,\u9078\u629E\u80A2B'` | CHECK_BOX \u7B49 | `[\"\u9078\u629E\u80A2A\",\"\u9078\u629E\u80A2B\"]` |\r\n| `''` | \u30E6\u30FC\u30B6\u30FC\u7CFB / \u914D\u5217\u7CFB | `[]` |\r\n\r\n#### \u914D\u5217\u30EA\u30C6\u30E9\u30EB `[...]`\uFF08\u30AB\u30F3\u30DE\u3092\u542B\u3080\u9078\u629E\u80A2\u306A\u3069\u660E\u793A\u6307\u5B9A\uFF09\r\n\r\n```sql\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E\uFF08\u8907\u6570\uFF09\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005) VALUES ('A\u793E', ['user1', 'user2'])\r\n\r\n-- \u30AB\u30F3\u30DE\u3092\u542B\u3080\u9078\u629E\u80A2\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u30BF\u30B0) VALUES ('A\u793E', ['\u9078\u629E\u80A2A', '\u9078\u629E\u80A2B,C'])\r\n-- \u2191 '\u9078\u629E\u80A2B,C' \u306F 1 \u3064\u306E\u5024\r\n```\r\n\r\n#### CASE WHEN / IF \u3067\u914D\u5217\u3092\u6307\u5B9A\r\n\r\n```sql\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E: IF() \u3067\u62C5\u5F53\u8005\u3092\u5206\u5C90\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005)\r\nVALUES ('A\u793E', IF(1 = 1, ['user1', 'user2'], 'user3'))\r\n\r\n-- CASE WHEN \u3067\u8907\u6570\u306E\u5206\u5C90\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u30BF\u30B0)\r\nVALUES ('B\u793E', CASE WHEN 1 = 0 THEN ['\u91CD\u8981', 'VIP'] ELSE '\u901A\u5E38' END)\r\n```\r\n\r\n> INSERT VALUES \u306E CASE WHEN / IF \u306F\u5B9A\u6570\u6761\u4EF6\u306E\u307F\u6709\u52B9\u3067\u3059\u3002 \r\n> \u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u73FE\u5728\u5024\u3092\u53C2\u7167\u3059\u308B\u6761\u4EF6\uFF08`\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5BFE\u8C61'` \u7B49\uFF09\u306F\u7A7A\u6587\u5B57\u3068\u3057\u3066\u8A55\u4FA1\u3055\u308C\u307E\u3059\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u306F UPDATE SET \u3067\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\uFF09\u3002\r\n\r\n#### INSERT SELECT \u3067\u306E\u540C\u578B\u30D5\u30A3\u30FC\u30EB\u30C9\u81EA\u52D5\u8EE2\u9001\r\n\r\n\u8EE2\u9001\u5143\u30FB\u8EE2\u9001\u5148\u304C\u540C\u3058\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u306E\u5834\u5408\u3001JSON \u3092\u81EA\u52D5\u89E3\u6790\u3057\u3066 API \u5F62\u5F0F\u306B\u5909\u63DB\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\n-- USER_SELECT \u2192 USER_SELECT: \u81EA\u52D5\u8EE2\u9001\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005) SELECT \u9867\u5BA2\u540D, \u62C5\u5F53\u8005 FROM APP88\r\n\r\n-- CHECK_BOX \u2192 CHECK_BOX: \u81EA\u52D5\u8EE2\u9001\r\nINSERT INTO APP89 (\u9867\u5BA2\u540D, \u30BF\u30B0) SELECT \u9867\u5BA2\u540D, \u30BF\u30B0 FROM APP88\r\n```\r\n\r\n### \u65E5\u6642\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u81EA\u52D5\u5909\u63DB\r\n\r\n\u65E5\u6642\uFF08DATETIME\uFF09\u30FB\u65E5\u4ED8\uFF08DATE\uFF09\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u3001\u3088\u304F\u4F7F\u308F\u308C\u308B\u8868\u8A18\u3092 kintone \u306E\u8981\u6C42\u5F62\u5F0F\u306B\u81EA\u52D5\u5909\u63DB\u3057\u307E\u3059\u3002 \r\n\u5909\u63DB\u306F\u30D6\u30E9\u30A6\u30B6\u306E\u30ED\u30FC\u30AB\u30EB\u30BF\u30A4\u30E0\u30BE\u30FC\u30F3\u3092\u57FA\u6E96\u3068\u3057\u307E\u3059\u3002\r\n\r\n#### DATETIME \u30D5\u30A3\u30FC\u30EB\u30C9\r\n\r\nkintone \u306F `YYYY-MM-DDTHH:MM:SSZ`\uFF08UTC\uFF09\u5F62\u5F0F\u3092\u8981\u6C42\u3057\u307E\u3059\u3002 \r\n\u4EE5\u4E0B\u306E\u5F62\u5F0F\u3067\u6307\u5B9A\u3059\u308B\u3068\u81EA\u52D5\u5909\u63DB\u3055\u308C\u307E\u3059\u3002\r\n\r\n| SQL \u5024\uFF08\u5165\u529B\uFF09 | kintone API \u9001\u4FE1\u5024\uFF08JST \u74B0\u5883\u306E\u5834\u5408\uFF09 |\r\n|---|---|\r\n| `'2026-04-05 12:00'` | `'2026-04-05T03:00:00Z'` |\r\n| `'2026-04-05 12:00:00'` | `'2026-04-05T03:00:00Z'` |\r\n| `'2026/04/05 12:00'` | `'2026-04-05T03:00:00Z'` |\r\n| `'2026-04-05T12:00'` | `'2026-04-05T03:00:00Z'` |\r\n| `'2026-04-05T03:00:00Z'` | `'2026-04-05T03:00:00Z'`\uFF08\u5909\u63DB\u306A\u3057\uFF09 |\r\n\r\n```sql\r\nINSERT INTO APP15 (\u4EF6\u540D, \u65E5\u6642) VALUES ('\u4F1A\u8B70', '2026-04-05 12:00')\r\n```\r\n\r\n#### DATE \u30D5\u30A3\u30FC\u30EB\u30C9\r\n\r\nkintone \u306F `YYYY-MM-DD` \u5F62\u5F0F\u3092\u8981\u6C42\u3057\u307E\u3059\u3002 \r\n\u30B9\u30E9\u30C3\u30B7\u30E5\u533A\u5207\u308A\u3092\u81EA\u52D5\u5909\u63DB\u3057\u307E\u3059\u3002\r\n\r\n| SQL \u5024\uFF08\u5165\u529B\uFF09 | kintone API \u9001\u4FE1\u5024 |\r\n|---|---|\r\n| `'2026/04/05'` | `'2026-04-05'` |\r\n| `'2026-04-05'` | `'2026-04-05'`\uFF08\u5909\u63DB\u306A\u3057\uFF09 |\r\n\r\n```sql\r\nINSERT INTO APP15 (\u4EF6\u540D, \u65E5\u4ED8) VALUES ('\u4F1A\u8B70', '2026/04/05')\r\n```\r\n\r\n> **\u30BF\u30A4\u30E0\u30BE\u30FC\u30F3:** DATETIME \u306E\u5909\u63DB\u306F\u30D6\u30E9\u30A6\u30B6\u306E\u30ED\u30FC\u30AB\u30EB\u6642\u523B\u3092 UTC \u306B\u5909\u63DB\u3057\u307E\u3059\u3002 \r\n> \u30D7\u30E9\u30B0\u30A4\u30F3\u304C\u52D5\u4F5C\u3059\u308B kintone \u74B0\u5883\u306E\u30BF\u30A4\u30E0\u30BE\u30FC\u30F3\u8A2D\u5B9A\u3068\u4E00\u81F4\u3055\u305B\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n---", uri: "ksql://language-reference/15-insert" }, "16-update": { heading: "16. UPDATE", text: "## 16. UPDATE\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u30D5\u30A3\u30FC\u30EB\u30C91 = \u50241, \u30D5\u30A3\u30FC\u30EB\u30C92 = \u50242 -- \u5024: \u30EA\u30C6\u30E9\u30EB / \u7B97\u8853\u5F0F / CASE WHEN / (SELECT ...) / \u30D0\u30C3\u30C1\u5909\u6570 @\u540D\u524D\r\nWHERE \u6761\u4EF6\r\n```\r\n\r\n\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u306B\u306F\u5358\u9805 `-` / `+` \u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08\u4F8B: `SET \u91D1\u984D = -5`\u3001`SET \u91D1\u984D = +0.5`\uFF09\u3002\u5358\u9805 `+` \u306F\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u76F4\u524D\u3060\u3051\u306B\u9650\u3089\u308C\u3001`+\u30D5\u30A3\u30FC\u30EB\u30C9` \u3084 `+(\u5F0F)`\u3001\u7B26\u53F7\u306E\u30CD\u30B9\u30C8\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002\u65E2\u5B58\u306E\u5358\u9805 `-` \u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u3084\u62EC\u5F27\u4ED8\u304D\u7B97\u8853\u5F0F\u306B\u3082\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u512A\u5148\u5EA6 = '\u9AD8', \u671F\u9650\u65E5 = '2025-03-31'\r\nWHERE \u62C5\u5F53\u8005 = '\u7530\u4E2D' AND \u5B8C\u4E86\u30D5\u30E9\u30B0 = '0'\r\n```\r\n\r\n### \u5225\u30C6\u30FC\u30D6\u30EB\u306E\u5024\u3067\u66F4\u65B0\uFF08UPDATE ... FROM\uFF09\r\n\r\n`#temp` \u307E\u305F\u306F\u5225\u30A2\u30D7\u30EA\u306E\u884C\u3092\u3001\u66F4\u65B0\u5148\u306E `$id` \u307E\u305F\u306F\u696D\u52D9\u30AD\u30FC\u3068\u5BFE\u5FDC\u4ED8\u3051\u3066\u8EE2\u8A18\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u8EE2\u8A18\u5024 = s.\u5143\u5024,\r\n \u51E6\u7406\u72B6\u614B = '\u5B8C\u4E86',\r\n \u91D1\u984D = \u91D1\u984D * 1.1\r\nFROM APP200 AS s\r\nWHERE APP100.$id = s.\u8EE2\u8A18\u5148ID\r\n AND APP100.\u6709\u52B9 = '1';\r\n```\r\n\r\n\u6587\u5B57\u5217\uFF081\u884C\uFF09\u307E\u305F\u306F\u6570\u5024\u306E\u696D\u52D9\u30AD\u30FC\u3067\u3082\u7D50\u5408\u3067\u304D\u307E\u3059\u3002\u30BD\u30FC\u30B91\u884C\u306B\u5BFE\u3057\u3066\u540C\u3058\u30AD\u30FC\u306E\u66F4\u65B0\u5148\u304C\u8907\u6570\u3042\u308B\u5834\u5408\u306F\u5168\u884C\u3092\u66F4\u65B0\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP4220\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u30A8\u30E9\u30FC',\r\n \u30A8\u30E9\u30FC\u5185\u5BB9 = e.\u30A8\u30E9\u30FC\u5185\u5BB9\r\nFROM APP200 AS e\r\nWHERE APP4220.\u9867\u5BA2\u30B3\u30FC\u30C9 = e.\u9867\u5BA2\u30B3\u30FC\u30C9;\r\n```\r\n\r\n\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3092\u4F7F\u3046\u5834\u5408\u306F\u540C\u3058\u30D0\u30C3\u30C1\u5185\u3067\u5148\u306B\u5B9F\u4F53\u5316\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nCREATE TEMP TABLE #src AS\r\nSELECT \u8EE2\u8A18\u5148ID, \u30A8\u30E9\u30FC\u5185\u5BB9 FROM APP200 WHERE \u51E6\u7406\u72B6\u614B = '\u30A8\u30E9\u30FC';\r\n\r\nUPDATE APP100\r\nSET \u30A8\u30E9\u30FC\u5185\u5BB9 = e.\u30A8\u30E9\u30FC\u5185\u5BB9\r\nFROM #src AS e\r\nWHERE APP100.$id = e.\u8EE2\u8A18\u5148ID;\r\n```\r\n\r\n> `REGEXP_REPLACE` / `REGEXP_SUBSTR` \u306A\u3069\u306E\u6B63\u898F\u8868\u73FE\u7D50\u679C\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u7D4C\u7531\u306E `UPDATE ... FROM` \u3067\u66F8\u304D\u623B\u3059\u5834\u5408\u3001\u30D6\u30E9\u30A6\u30B6\uFF0FNode \u3068\u305D\u306E\u7248\u306B\u3088\u308B\u7D50\u679C\u5DEE\u304C\u4FDD\u5B58\u30C7\u30FC\u30BF\u306E\u5DEE\u306B\u306A\u308A\u307E\u3059\u3002\u66F8\u304D\u623B\u3057\u306B\u4F7F\u3046\u5B9F\u884C\u9762\u3068\u7248\u3092\u56FA\u5B9A\u3057\u3001\u4E8B\u524D\u306B SELECT \u3067\u7D50\u679C\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n- \u30BD\u30FC\u30B9\u306F `#temp` \u307E\u305F\u306F `APP[@profile]`\u3002CTE\u30FB\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u975E\u5BFE\u5FDC\u3067\u3059\u3002\r\n- \u7D50\u5408\u6761\u4EF6\u306F\u66F4\u65B0\u5148\u3068\u30BD\u30FC\u30B9\u5217\u306E\u5358\u4E00\u7B49\u5024\u30921\u3064\u3060\u3051\u6307\u5B9A\u3057\u307E\u3059\u3002\u66F4\u65B0\u5148\u30AD\u30FC\u306F `$id`\u3001\u6587\u5B57\u5217\uFF081\u884C\uFF09\u3001\u6570\u5024\u306B\u5BFE\u5FDC\u3057\u307E\u3059\u3002\r\n- `$id` \u306E\u30BD\u30FC\u30B9\u30AD\u30FC\u306F\u6B63\u306E\u5B89\u5168\u6574\u6570\u3067\u3059\u3002\u696D\u52D9\u30AD\u30FC\u306E\u30BD\u30FC\u30B9\u5024\u306F\u7A7A\u306B\u3067\u304D\u305A\u3001\u6B63\u898F\u5316\u5F8C\u306B\u91CD\u8907\u3059\u308B\u5834\u5408\u306F\u66F8\u304D\u8FBC\u307F\u524D\u306B\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002\r\n- \u6587\u5B57\u5217\u30AD\u30FC\u306F\u524D\u5F8C\u7A7A\u767D\u30FB\u5927\u6587\u5B57\u5C0F\u6587\u5B57\u3092\u5909\u63DB\u305B\u305A\u5B8C\u5168\u4E00\u81F4\u3057\u307E\u3059\u3002\u6570\u5024\u30AD\u30FC\u306F\u6D6E\u52D5\u5C0F\u6570\u70B9\u3078\u5909\u63DB\u305B\u305A\u3001\u7B26\u53F7\u30FB\u5148\u982D\u30BC\u30ED\u30FB\u5C0F\u6570\u672B\u5C3E\u30BC\u30ED\u309210\u9032\u6587\u5B57\u5217\u3068\u3057\u3066\u6B63\u898F\u5316\u3057\u307E\u3059\u3002\r\n- kintone\u306E\u6587\u5B57\u5217\uFF081\u884C\uFF09`in` \u306F\u5148\u982D64\u6587\u5B57\u304C\u540C\u3058\u884C\u3092\u904E\u5270\u53D6\u5F97\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u304C\u3001\u53D6\u5F97\u5F8C\u306B\u5168\u6587\u5B57\u3067\u518D\u7167\u5408\u3059\u308B\u305F\u3081\u8AA4\u66F4\u65B0\u3057\u307E\u305B\u3093\u3002\u904E\u5270\u53D6\u5F97\u884C\u3082 `maxRecords` \u306E\u8AAD\u307F\u53D6\u308A\u4EF6\u6570\u3078\u542B\u307E\u308C\u307E\u3059\u3002\r\n- \u30BD\u30FC\u30B9\u5074\u306E\u540C\u3058\u6B63\u898F\u5316\u30AD\u30FC\u306F\u975E\u6C7A\u5B9A\u306B\u306A\u308B\u305F\u3081\u30A8\u30E9\u30FC\u3067\u3059\u3002\u66F4\u65B0\u5148\u5074\u306E\u540C\u3058\u30AD\u30FC\u306F\u6C7A\u5B9A\u7684\u306B\u5168\u884C\u66F4\u65B0\u3057\u307E\u3059\u3002\r\n- \u30BD\u30FC\u30B9 alias \u306F\u7D50\u5408\u6761\u4EF6\u3068 `SET alias.field` \u4EE5\u5916\u3067\u306F\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\u3002\r\n- `SOURCE_FIELD` \u306F\u30B9\u30AB\u30E9\u30FC\u578B\u306E\u307F\u5BFE\u5FDC\u3057\u307E\u3059\u3002\u914D\u5217\u30FB\u30E6\u30FC\u30B6\u30FC/\u7D44\u7E54/\u30B0\u30EB\u30FC\u30D7\u9078\u629E\u30FB\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\u306F\u975E\u5BFE\u5FDC\u3067\u3059\u3002\r\n- \u5B9F\u30A2\u30D7\u30EA\u30BD\u30FC\u30B9\u306F `maxRecords` \u8D85\u904E\u6642\u306B\u5E38\u306B\u30A8\u30E9\u30FC\u3068\u306A\u308A\u3001\u6697\u9ED9\u306E\u4E00\u90E8\u66F4\u65B0\u3092\u884C\u3044\u307E\u305B\u3093\u3002\r\n- `SET` \u3084\u30D5\u30A3\u30EB\u30BF\u304C\u53C2\u7167\u3059\u308B\u30BD\u30FC\u30B9\u5217\u304C\u30BD\u30FC\u30B9\u306B\u5B58\u5728\u3057\u306A\u3044\u5834\u5408\u3001\u66F8\u304D\u8FBC\u307F\u524D\u306B\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002\r\n- \u7D50\u5408\u7B49\u5024\u306F\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E `AND` \u9023\u9396\u306B\u7F6E\u304D\u307E\u3059\u3002`OR` / `NOT` \u306E\u914D\u4E0B\u306B\u7D50\u5408\u7B49\u5024\u3092\u66F8\u304F\u3068\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\uFF08\u30BF\u30FC\u30B2\u30C3\u30C8\u306E\u307F\u3092\u6761\u4EF6\u306B\u3057\u305F\u62EC\u5F27\u5185 `OR` \u306F\u4F7F\u3048\u307E\u3059\uFF09\u3002\r\n- **\u89AA\u30EC\u30B3\u30FC\u30C9\u306E `UPDATE` \u9650\u5B9A**\u3067\u3059\u3002\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306B\u5BFE\u3059\u308B `UPDATE ... FROM` \u306F\u975E\u5BFE\u5FDC\u3067\u3059\u3002\r\n\r\n### SET \u3067\u306E\u6587\u5B57\u5217\u95A2\u6570\r\n\r\n\u89AA\u30EC\u30B3\u30FC\u30C9\u306E\u901A\u5E38\u306E `UPDATE` \u3067\u306F\u3001SET \u306E\u53F3\u8FBA\u306B\u6587\u5B57\u5217\u95A2\u6570\u3092\u76F4\u63A5\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\u95A2\u6570\u306F\u66F4\u65B0\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u3054\u3068\u306B\u8A55\u4FA1\u3055\u308C\u3001SET \u5BFE\u8C61\u3068\u306F\u5225\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3082\u53C2\u7167\u3067\u304D\u307E\u3059\u3002\u623B\u308A\u5024\u306F\u95A2\u6570\u306E\u610F\u5473\u578B\u3092\u5F15\u304D\u7D99\u304E\u3001\u5024\u306E\u898B\u305F\u76EE\u304B\u3089\u6570\u5024\uFF0F\u6587\u5B57\u5217\u3092\u518D\u5224\u5B9A\u3057\u307E\u305B\u3093\u3002\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u6B63\u898F\u5316\u540D = UPPER(\u540D\u79F0),\r\n \u30B3\u30FC\u30C9 = LPAD(\u30B3\u30FC\u30C9, 5, '0')\r\nWHERE $id IN (1, 2, 3)\r\n```\r\n\r\n`UPPER` / `CONCAT` / `REPLACE` / `SUBSTRING` / `LEFT` / `RIGHT` / `TRANSLATE` / `REGEXP_LIKE` / `REGEXP_REPLACE` / `REGEXP_SUBSTR` \u306A\u3069\u306E\u6587\u5B57\u5217\u95A2\u6570\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002`LPAD('7', 5, '0')` \u3068 `REGEXP_LIKE(...)` \u306E\u7D50\u679C\u306F\u3001\u898B\u305F\u76EE\u304C\u6570\u5024\u3067\u3082\u6587\u5B57\u5217\u306E\u307E\u307E\u66F8\u304D\u8FBC\u307E\u308C\u307E\u3059\u3002`VALIDATE ONLY` \u3068 `ON ERROR SKIP` \u306F\u3001\u95A2\u6570\u3092\u8A55\u4FA1\u3057\u305F\u5F8C\u306E\u5024\u3092\u691C\u8A3C\u3057\u307E\u3059\u3002\r\n\r\n\u3053\u308C\u306F\u66F8\u304D\u8FBC\u307F\u5019\u88DC\u306B\u5BFE\u3059\u308B\u7D44\u307F\u8FBC\u307F\u5236\u7D04\u691C\u8A3C\u3067\u3059\u3002CHECK \u306E\u8A55\u4FA1\u884C\u306F\u5225\u3067\u3001\u901A\u5E38 UPDATE \u306F\u66F4\u65B0\u524D\u306E\u65E2\u5B58\u5024\u3092\u53C2\u7167\u3057\u307E\u3059\u3002\u65B0\u5024\u3092\u691C\u67FB\u3059\u308B\u5834\u5408\u306F SET \u5F0F\u3092 CHECK \u306B\u518D\u63B2\u3057\u3066\u304F\u3060\u3055\u3044\u3002INSERT/UPSERT/UPDATE FROM \u3092\u542B\u3080\u6587\u7A2E\u5225\u306E\u8A55\u4FA1\u884C\u306F \xA717.3 \u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n\u6B63\u898F\u8868\u73FE\u306E\u30DB\u30B9\u30C8\u5DEE\u306F\u4FDD\u5B58\u30C7\u30FC\u30BF\u306E\u5DEE\u306B\u306A\u308A\u5F97\u308B\u305F\u3081\u3001\u66F8\u304D\u8FBC\u307F\u306B\u4F7F\u3046\u5B9F\u884C\u9762\u3068\u7248\u3092\u56FA\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n\u6B21\u306E\u7BC4\u56F2\u306F\u975E\u5BFE\u5FDC\u3067\u3059\u3002\r\n\r\n- `SET n = LENGTH(s) * 1` \u306E\u3088\u3046\u306B\u7B97\u8853\u5F0F\u306E\u4E2D\u3078\u6587\u5B57\u5217\u95A2\u6570\u3092\u5165\u308C\u308B\u3053\u3068\r\n- `SET a = b` \u306E\u3088\u3046\u306B\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3060\u3051\u3092\u53F3\u8FBA\u3078\u6307\u5B9A\u3059\u308B\u3053\u3068\r\n- `UPDATE ... FROM` \u307E\u305F\u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306E SET \u53F3\u8FBA\u3078\u6587\u5B57\u5217\u95A2\u6570\u3092\u76F4\u63A5\u6307\u5B9A\u3059\u308B\u3053\u3068\uFF08`UPDATE ... FROM` \u306E `SET a = src.b` \u306F\u5F93\u6765\u3069\u304A\u308A\u4F7F\u7528\u3067\u304D\u307E\u3059\uFF09\r\n\r\n\u307E\u305F\u3001\u89AA\u30EC\u30B3\u30FC\u30C9 DML \u306E WHERE \u53E5\u3067\u306F\u6587\u5B57\u5217\u95A2\u6570\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002SET \u3067\u95A2\u6570\u3092\u4F7F\u3048\u308B\u3088\u3046\u306B\u306A\u3063\u3066\u3082\u3001`WHERE LEFT(\u90F5\u4FBF\u756A\u53F7, 3) = '100'` \u306E\u3088\u3046\u306A\u7D5E\u308A\u8FBC\u307F\u306F\u62D2\u5426\u3055\u308C\u307E\u3059\u3002\u4E0D\u6B63\u306A\u884C\u3060\u3051\u3092\u6B63\u898F\u5316\u3059\u308B\u5834\u5408\u306F\u3001\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3067\u5BFE\u8C61\u3068\u5909\u63DB\u5024\u3092\u4F5C\u308A\u3001`UPDATE ... FROM` \u3067\u66F8\u304D\u623B\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nCREATE TEMP TABLE #norm AS\r\nSELECT $id AS \u5BFE\u8C61id,\r\n REPLACE(REPLACE(\u96FB\u8A71\u756A\u53F7, '-', ''), ' ', '') AS \u6B63\u898F\u5316\r\nFROM APP100\r\nWHERE \u6761\u4EF6;\r\n\r\nUPDATE APP100\r\nSET \u96FB\u8A71\u756A\u53F7 = n.\u6B63\u898F\u5316\r\nFROM #norm AS n\r\nWHERE APP100.$id = n.\u5BFE\u8C61id;\r\n```\r\n\r\n### SET \u3067\u306E\u7B97\u8853\u5F0F\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u91D1\u984D = \u91D1\u984D * 1.1\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5BFE\u8C61'\r\n```\r\n\r\n### SET \u3067\u306E\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\r\n\r\nSET \u306E\u53F3\u8FBA\u306B `(SELECT ...)` \u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002 \r\n\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u5B9F\u884C\u524D\u306B 1 \u56DE\u3060\u3051\u8A55\u4FA1\u3055\u308C\u3001\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u5168\u4EF6\u306B\u540C\u3058\u5024\u304C\u8A2D\u5B9A\u3055\u308C\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u540C\u30A2\u30D7\u30EA\u306E\u6700\u5927\u5024\u3067\u30BB\u30C3\u30C8\r\nUPDATE APP88 SET \u4E0A\u9650\u8CBB\u7528 = (SELECT MAX(\u5408\u8A08\u8CBB\u7528) FROM APP88)\r\nWHERE \u78BA\u5EA6 in ('80%', '100%')\r\n\r\n-- \u5225\u30A2\u30D7\u30EA\u306E\u5024\u3067\u30BB\u30C3\u30C8\r\nUPDATE APP89 SET \u57FA\u6E96\u91D1\u984D = (SELECT AVG(\u5408\u8A08\u8CBB\u7528) FROM APP88 WHERE \u78BA\u5EA6 in ('100%'))\r\nWHERE \u9867\u5BA2\u30E9\u30F3\u30AF in ('A')\r\n```\r\n\r\n\u8907\u6570\u30D5\u30A3\u30FC\u30EB\u30C9\u3078\u306E\u6DF7\u5728\u6307\u5B9A\u3082\u53EF\u80FD\u3067\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP88\r\nSET \u5408\u8A08\u8CBB\u7528 = \u5408\u8A08\u8CBB\u7528 * 1.1,\r\n \u4E0A\u9650\u8CBB\u7528 = (SELECT MAX(\u5408\u8A08\u8CBB\u7528) FROM APP88),\r\n \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u66F4\u65B0\u6E08\u307F'\r\nWHERE \u78BA\u5EA6 in ('80%', '100%')\r\n```\r\n\r\n**\u5236\u7D04:**\r\n\r\n| \u9805\u76EE | \u5185\u5BB9 |\r\n|---|---|\r\n| \u8FD4\u5374\u884C\u6570 | 1 \u884C 1 \u5217\u306E\u307F\uFF080 \u884C\u30FB2 \u884C\u4EE5\u4E0A\u306F\u30A8\u30E9\u30FC\u3002GROUP BY \u306A\u3057\u306E\u96C6\u8A08\u30B5\u30D6\u30AF\u30A8\u30EA\u306F 0 \u4EF6\u3067\u3082 1 \u884C = `0` \u3092\u8FD4\u3059\u305F\u3081\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u305B\u3093 \u2014 \xA78\uFF09 |\r\n| \u76F8\u95A2\u30B5\u30D6\u30AF\u30A8\u30EA | \u975E\u5BFE\u5FDC\uFF08\u5916\u5074\u30C6\u30FC\u30D6\u30EB\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u53C2\u7167\u4E0D\u53EF\uFF09 |\r\n| \u30B5\u30D6\u30AF\u30A8\u30EA\u5F8C\u306E\u7B97\u8853 | \u975E\u5BFE\u5FDC \u2014 \u7B97\u8853\u306F\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u884C\u3046 |\r\n\r\n```sql\r\n-- NG: \u30B5\u30D6\u30AF\u30A8\u30EA\u5F8C\u306E\u7B97\u8853\r\nUPDATE APP88 SET \u4E0A\u9650\u8CBB\u7528 = (SELECT AVG(\u5408\u8A08\u8CBB\u7528) FROM APP88) * 1.1 WHERE ...\r\n\r\n-- OK: \u7B97\u8853\u3092\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u5B9F\u884C\r\nUPDATE APP88 SET \u4E0A\u9650\u8CBB\u7528 = (SELECT AVG(\u5408\u8A08\u8CBB\u7528) * 1.1 FROM APP88) WHERE ...\r\n```\r\n\r\n---\r\n\r\n### SET \u3067\u306E CASE WHEN\r\n\r\nSET \u306E\u53F3\u8FBA\u306B CASE WHEN \u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u9867\u5BA2\u30E9\u30F3\u30AF = CASE\r\n WHEN \u91D1\u984D >= 100000 THEN 'S'\r\n WHEN \u91D1\u984D >= 10000 THEN 'A'\r\n ELSE 'B'\r\n END\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5BFE\u8C61'\r\n```\r\n\r\n\u7B97\u8853\u5F0F\u3068 CASE WHEN \u3092\u540C\u6642\u306B\u6307\u5B9A\u3059\u308B\u3053\u3068\u3082\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u5408\u8A08 = \u5358\u4FA1 * \u6570\u91CF,\r\n \u30E9\u30F3\u30AF = CASE\r\n WHEN \u5358\u4FA1 >= 10000 THEN 'S'\r\n ELSE 'A'\r\n END\r\nWHERE \u62C5\u5F53\u8005 = '\u7530\u4E2D'\r\n```\r\n\r\n#### THEN / ELSE \u306B\u914D\u5217\u30EA\u30C6\u30E9\u30EB\u3092\u6307\u5B9A\r\n\r\n\u30E6\u30FC\u30B6\u30FC\u9078\u629E\u30FB\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u7B49\u306E\u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u5BFE\u3057\u3066\u3001\u6761\u4EF6\u306B\u5FDC\u3058\u305F\u5024\u3092\u66F8\u304D\u8FBC\u3081\u307E\u3059\u3002 \r\n\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u306F `getFields()` \u3067\u81EA\u52D5\u53D6\u5F97\u3055\u308C\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E: \u512A\u5148\u5EA6\u306B\u5FDC\u3058\u3066\u62C5\u5F53\u8005\u3092\u5207\u308A\u66FF\u3048\r\nUPDATE APP89\r\nSET \u62C5\u5F53\u8005 = CASE\r\n WHEN \u512A\u5148\u5EA6 = '\u9AD8' THEN ['user1', 'user2']\r\n WHEN \u512A\u5148\u5EA6 = '\u4E2D' THEN 'user3'\r\n ELSE ''\r\n END\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u672A\u7740\u624B'\r\n\r\n-- IF() \u77ED\u7E2E\u8A18\u6CD5: \u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u3092\u5206\u5C90\r\nUPDATE APP89\r\nSET \u30BF\u30B0 = IF(\u9867\u5BA2\u30E9\u30F3\u30AF = 'A', ['\u91CD\u8981', 'VIP'], '\u901A\u5E38')\r\nWHERE \u62C5\u5F53\u8005 = 'user1'\r\n\r\n-- \u6587\u5B57\u5217\u30D5\u30A3\u30FC\u30EB\u30C9\u3068\u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u6DF7\u5728\r\nUPDATE APP89\r\nSET \u9867\u5BA2\u30E9\u30F3\u30AF = CASE WHEN \u91D1\u984D >= 100000 THEN 'S' ELSE 'A' END,\r\n \u62C5\u5F53\u8005 = CASE WHEN \u91D1\u984D >= 100000 THEN ['user1', 'user2'] ELSE 'user3' END\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5BFE\u8C61'\r\n```\r\n\r\n> **WHERE \u53E5\u306F\u5FC5\u9808\u3067\u3059\u3002** \u5168\u4EF6\u66F4\u65B0\u3092\u9632\u3050\u305F\u3081\u3001WHERE \u306A\u3057\u306E UPDATE \u306F\u69CB\u6587\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002 \r\n> \u6CE8: CLI \u306B\u306F `--allow-without-where` \u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u3059\u304C\u3001\u73FE\u884C\u5B9F\u88C5\u3067\u306F UPDATE/DELETE \u306E\u6587\u6CD5\u4E0A WHERE \u304C\u5FC5\u9808\u3067\u3059\u3002\r\n\r\n> **\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0:** \u5B9F\u884C\u524D\u306B\u5BFE\u8C61\u4EF6\u6570\u3092\u8868\u793A\u3057\u3066\u78BA\u8A8D\u3092\u6C42\u3081\u307E\u3059\u3002 \r\n> \u30AD\u30E3\u30F3\u30BB\u30EB\u3059\u308B\u3068\u66F4\u65B0\u306F\u884C\u308F\u308C\u307E\u305B\u3093\u3002\r\n\r\n> **\u30D7\u30ED\u30BB\u30B9\u7BA1\u7406\u306E\u30B9\u30C6\u30FC\u30BF\u30B9\u30FB\u4F5C\u696D\u8005\u306F\u66F4\u65B0\u4E0D\u53EF\u3067\u3059\u3002** \r\n> \u3053\u308C\u3089\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u306F kintone \u306E `/k/v1/records.json` \u3067\u306F\u5909\u66F4\u3067\u304D\u305A\u3001\u5C02\u7528\u306E `/k/v1/records/status.json` API \u304C\u5FC5\u8981\u3067\u3059\u3002 \r\n> kSQL \u306E UPDATE \u5BFE\u8C61\u5916\u3068\u306A\u308A\u307E\u3059\u3002\r\n\r\n### SET \u3067\u306E\u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\r\n\r\n\u30E6\u30FC\u30B6\u30FC\u9078\u629E\u30FB\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u7B49\u306E\u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\u3078\u306E SET \u3092\u30B5\u30DD\u30FC\u30C8\u3057\u307E\u3059\u3002 \r\n\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u306F\u5B9F\u884C\u524D\u306B `getFields()` \u3067\u81EA\u52D5\u53D6\u5F97\u3057\u307E\u3059\u3002\r\n\r\n#### \u30AB\u30F3\u30DE\u533A\u5207\u308A\u6587\u5B57\u5217\r\n\r\n```sql\r\n-- \u30E6\u30FC\u30B6\u30FC\u9078\u629E\u3092\u66F4\u65B0\r\nUPDATE APP89 SET \u62C5\u5F53\u8005 = 'user1,user2' WHERE \u9867\u5BA2\u540D = 'A\u793E'\r\n\r\n-- \u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u3092\u66F4\u65B0\r\nUPDATE APP89 SET \u30BF\u30B0 = '\u91CD\u8981,VIP' WHERE \u9867\u5BA2\u30E9\u30F3\u30AF = 'A'\r\n\r\n-- \u7A7A\u306B\u3059\u308B\r\nUPDATE APP89 SET \u62C5\u5F53\u8005 = '' WHERE \u9867\u5BA2\u540D = 'A\u793E'\r\n```\r\n\r\n#### \u914D\u5217\u30EA\u30C6\u30E9\u30EB `[...]`\r\n\r\n```sql\r\n-- \u30AB\u30F3\u30DE\u3092\u542B\u3080\u9078\u629E\u80A2\r\nUPDATE APP89 SET \u30BF\u30B0 = ['\u9078\u629E\u80A2A', '\u9078\u629E\u80A2B,C'] WHERE \u9867\u5BA2\u30E9\u30F3\u30AF = 'A'\r\n```\r\n\r\n#### \u5BFE\u8C61\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u3068\u5909\u63DB\u30EB\u30FC\u30EB\r\n\r\n| \u30D5\u30A3\u30FC\u30EB\u30C9\u578B | SQL \u8A18\u8FF0\u4F8B | kintone API \u9001\u4FE1\u5024 |\r\n|---|---|---|\r\n| USER_SELECT / ORGANIZATION_SELECT / GROUP_SELECT | `'user1,user2'` | `[{\"code\":\"user1\"},{\"code\":\"user2\"}]` |\r\n| CHECK_BOX / MULTI_SELECT | `'\u9078\u629E\u80A2A,\u9078\u629E\u80A2B'` | `[\"\u9078\u629E\u80A2A\",\"\u9078\u629E\u80A2B\"]` |\r\n| \u7A7A\u306B\u3059\u308B\uFF08\u30E6\u30FC\u30B6\u30FC\u7CFB\u30FB\u914D\u5217\u7CFB\uFF09 | `''` | `[]` |\r\n| DATETIME | `'2026-04-05 12:00'` | `'2026-04-05T03:00:00Z'`\uFF08\u30ED\u30FC\u30AB\u30EB\u2192UTC\uFF09 |\r\n| DATE | `'2026/04/05'` | `'2026-04-05'` |\r\n| CREATOR / MODIFIER | \u2014 | **\u66F4\u65B0\u4E0D\u53EF**\uFF08kintone \u5236\u7D04\uFF09 |\r\n\r\n```sql\r\n-- \u65E5\u6642\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u66F4\u65B0\r\nUPDATE APP15 SET \u65E5\u6642 = '2026-04-05 12:00' WHERE $id = 9\r\nUPDATE APP15 SET \u65E5\u4ED8 = '2026/04/05' WHERE $id = 9\r\n```\r\n\r\n---", uri: "ksql://language-reference/16-update" }, "17-upsert": { heading: "17. UPSERT", text: "## 17. UPSERT\r\n\r\n\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u5024\u3067\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u3092\u691C\u7D22\u3057\u3001\u4E00\u81F4\u3059\u308C\u3070\u66F4\u65B0\u30FB\u306A\u3051\u308C\u3070\u65B0\u898F\u767B\u9332\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nUPSERT INTO \u30C6\u30FC\u30D6\u30EB\u540D (\u30D5\u30A3\u30FC\u30EB\u30C91, \u30D5\u30A3\u30FC\u30EB\u30C92, ...)\r\nVALUES (\u50241, \u50242, ...)\r\nON DUPLICATE (\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9)\r\n```\r\n\r\n### VALUES \u306B\u3088\u308B UPSERT\r\n\r\n```sql\r\nUPSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, \u91D1\u984D)\r\nVALUES ('C001', '\u7530\u4E2D\u5546\u5E97', 50000)\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\n```\r\n\r\n\u8907\u6570\u30EC\u30B3\u30FC\u30C9\u306E\u4E00\u62EC UPSERT:\r\n\r\n```sql\r\nUPSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, \u91D1\u984D)\r\nVALUES ('C001', '\u7530\u4E2D\u5546\u5E97', 50000),\r\n ('C002', '\u9234\u6728\u5546\u4E8B', 80000)\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\n```\r\n\r\n\u8907\u5408\u30AD\u30FC:\r\n\r\n```sql\r\nUPSERT INTO APP100 (\u5E74\u5EA6, \u6708, \u62C5\u5F53\u8005, \u58F2\u4E0A)\r\nVALUES ('2025', '4', '\u7530\u4E2D', 150000)\r\nON DUPLICATE (\u5E74\u5EA6, \u6708, \u62C5\u5F53\u8005)\r\n```\r\n\r\n### SELECT \u306B\u3088\u308B UPSERT\r\n\r\n\u5225\u30A2\u30D7\u30EA\u306E\u30C7\u30FC\u30BF\u3092\u30BD\u30FC\u30B9\u306B\u3057\u3066 UPSERT \u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nUPSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, \u5408\u8A08\u91D1\u984D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, SUM(\u91D1\u984D)\r\nFROM APP200\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u78BA\u5B9A'\r\nGROUP BY \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\n```\r\n\r\n- SELECT \u306E\u5217\u6570\u3068 UPSERT \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u6570\u304C\u4E00\u81F4\u3057\u306A\u3044\u5834\u5408\u306F\u30A8\u30E9\u30FC\r\n- SELECT \u5074\u306F SIMPLE / FULL_SCAN \u3092\u81EA\u52D5\u5224\u5B9A\uFF08JOIN\u30FBGROUP BY\u30FB\u95A2\u6570\u3082\u4F7F\u7528\u53EF\uFF09\r\n- USER_SELECT / CHECK_BOX \u7B49\u306E\u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u3001\u8EE2\u9001\u5143\u30FB\u8EE2\u9001\u5148\u304C\u540C\u578B\u306E\u5834\u5408\u306B\u81EA\u52D5\u5909\u63DB\r\n\r\n### \u8907\u5408\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u542B\u3080 UPSERT\r\n\r\nINSERT \u3068\u540C\u69D8\u306B\u3001\u30E6\u30FC\u30B6\u30FC\u9078\u629E\u30FB\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u7B49\u3078\u306E\u30AB\u30F3\u30DE\u533A\u5207\u308A\u6587\u5B57\u5217\u30FB\u914D\u5217\u30EA\u30C6\u30E9\u30EB\u6307\u5B9A\u304C\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\n-- VALUES: \u30AB\u30F3\u30DE\u533A\u5207\u308A\u3067\u30E6\u30FC\u30B6\u30FC\u9078\u629E\r\nUPSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005, \u30BF\u30B0)\r\nVALUES ('A\u793E', 'user1,user2', '\u91CD\u8981,VIP')\r\nON DUPLICATE (\u9867\u5BA2\u540D)\r\n\r\n-- SELECT: \u540C\u578B\u30D5\u30A3\u30FC\u30EB\u30C9\u9593\u306F\u81EA\u52D5\u8EE2\u9001\r\nUPSERT INTO APP89 (\u9867\u5BA2\u540D, \u62C5\u5F53\u8005)\r\nSELECT \u9867\u5BA2\u540D, \u62C5\u5F53\u8005 FROM APP88\r\nON DUPLICATE (\u9867\u5BA2\u540D)\r\n```\r\n\r\n### \u7D50\u679C\u8868\u793A\r\n\r\n| \u9805\u76EE | \u5185\u5BB9 |\r\n|------|------|\r\n| \u767B\u9332\u4EF6\u6570 | \u65B0\u898F\u767B\u9332\u3055\u308C\u305F\u30EC\u30B3\u30FC\u30C9\u6570 |\r\n| \u66F4\u65B0\u4EF6\u6570 | \u66F4\u65B0\u3055\u308C\u305F\u30EC\u30B3\u30FC\u30C9\u6570 |\r\n\r\n> \u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u4E00\u81F4\u3059\u308B\u30EC\u30B3\u30FC\u30C9\u304C\u8907\u6570\u3042\u308B\u5834\u5408\u306F\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n---\r\n\r\n## 17.1 VALIDATE ONLY\uFF08\u66F8\u304D\u8FBC\u307F\u524D\u691C\u8A3C\uFF09\r\n\r\n`INSERT` / `UPSERT` / `UPDATE` \u306E\u672B\u5C3E\u306B `VALIDATE ONLY` \u3092\u4ED8\u3051\u308B\u3068\u3001\u5019\u88DC\u884C\u3092\u5168\u4EF6\u691C\u8A3C\u3057\u3001kintone \u306E POST / PUT / DELETE API\u3092\u547C\u3070\u305A\u306B\u30A8\u30E9\u30FC\u4E00\u89A7\u3092\u8FD4\u3057\u307E\u3059\u3002\u89AA\u30EC\u30B3\u30FC\u30C9DML\u306E\u307F\u5BFE\u5FDC\u3057\u3001\u30B5\u30D6\u30C6\u30FC\u30D6\u30EBDML\u3001`DELETE`\u3001`REORDER`\u306B\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002\r\n\r\n```sql\r\nINSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nVALUES ('C001', 100), ('', -1)\r\nVALIDATE ONLY;\r\n\r\nUPSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP200\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\nVALIDATE ONLY;\r\n\r\nUPDATE APP100 SET \u91D1\u984D = \u91D1\u984D * 1.1\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u6709\u52B9'\r\nVALIDATE ONLY;\r\n```\r\n\r\n\u691C\u8A3C\u5BFE\u8C61\u306F\u5FC5\u9808\u3001\u6570\u5024\u30FB\u65E5\u4ED8\u30FB\u6642\u523B\u30FB\u65E5\u6642\u3001\u6570\u5024\u7BC4\u56F2\u3001\u6587\u5B57\u5217\u9577\u3001\u9078\u629E\u80A2\u3001UPSERT\u30AD\u30FC\u306E\u7A7A\u5024\u30FB\u30BD\u30FC\u30B9\u5185\u91CD\u8907\u3067\u3059\uFF08`UPDATE`/`UPSERT` update \u5206\u5C90\u306F\u5F8C\u8FF0\u306E post-image \u306B\u3088\u308A\u30EC\u30B3\u30FC\u30C9\u5168\u4F53\u30FB\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u884C\u3082\u5BFE\u8C61\uFF09\u30021\u884C\u306B\u8907\u6570\u306E\u554F\u984C\u304C\u3042\u308C\u3070\u30A8\u30E9\u30FC\u3082\u8907\u6570\u884C\u306B\u306A\u308A\u307E\u3059\u3002\u7D50\u679C\u306B\u306F `validatedRows` / `validRows` / `invalidRows` / `errorCount` \u3068\u3001\u5165\u529B\u30DA\u30A4\u30ED\u30FC\u30C9\u5217\u304A\u3088\u3073 `$err_*` \u8A3A\u65AD\u5217\uFF08`$err_statement` / `$err_operation` / `$err_row` / `$err_field` / `$err_code` / `$err_message` / `$err_value` / `$err_subtable` / `$err_subrow` / `$err_subrow_id` \u306E10\u5217\u3002v3.9.0 \u4EE5\u964D\uFF09\u304C\u542B\u307E\u308C\u307E\u3059\u3002\u5B50\u30BB\u30EB\u4EE5\u5916\u306E\u9055\u53CD\u3067\u306F\u672B\u5C3E4\u5217\uFF08`$err_value` / `$err_subtable` / `$err_subrow` / `$err_subrow_id`\uFF09\u306F\u7A7A\u6587\u5B57\u3067\u3059\u3002\r\n\r\n\u8907\u6587\u30D0\u30C3\u30C1\u3067\u306F `VALIDATE ONLY INTO #err` \u3068\u3059\u308B\u3068\u3001\u540C\u3058\u30A8\u30E9\u30FC\u884C\u3092\u5F8C\u7D9A\u6587\u304B\u3089\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3068\u3057\u3066\u53C2\u7167\u3067\u304D\u307E\u3059\u3002\u540C\u540D `#err` \u306F\u5165\u529B\u5217\u69CB\u6210\u304C\u540C\u3058\u5834\u5408\u3060\u3051\u8FFD\u8A18\u3067\u304D\u3001\u7570\u306A\u308Bschema\u307E\u305F\u306F `tempTableMaxRows` \u8D85\u904E\u306F\u65E2\u5B58\u884C\u3092\u5909\u66F4\u305B\u305A\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n```sql\r\nINSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D FROM #source\r\nVALIDATE ONLY INTO #err;\r\nSELECT * FROM #err;\r\n```\r\n\r\n- `VALIDATE ONLY` \u306Fread-only\u6271\u3044\u3067\u3001MCP\u3067\u306F `ksql_query`\u3001CLI\u3067\u306F `--allow-dml`\u306A\u3057\u3001\u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306F\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0\u306A\u3057\u3067\u5B9F\u884C\u3067\u304D\u307E\u3059\r\n- \u66F8\u304D\u8FBC\u307F\u5148\u306B NUMBER \u5217\u304C\u3042\u308B\u5834\u5408\u3001\u901A\u5E38 DML \u3068\u540C\u3058\u304F\u904B\u7528\u74B0\u5883\u306E `app/settings.json` \u304B\u3089 `numberPrecision` \u3092\u53D6\u5F97\u3057\u3001**\u6574\u6570\u90E8**\u304C `digits - decimalPlaces` \u6841\u3092\u8D85\u3048\u308B\u5024\u3092\u66F8\u304D\u8FBC\u307F\u524D\u306B\u691C\u51FA\u3057\u307E\u3059\uFF08`ERR_NUMBER_INTEGER_DIGITS`\uFF09\u3002kintone \u3082\u6574\u6570\u8D85\u904E\u306F\u5168\u9762\u3067 `CB_VA01` \u62D2\u5426\u3059\u308B\u305F\u3081\u3001\u3053\u308C\u306F\u305D\u306E\u5224\u65AD\u306E\u524D\u5012\u3057\u3067\u3059\r\n- **\u5C0F\u6570\u90E8\u306F kSQL \u3067\u306F\u691C\u8A3C\u3057\u307E\u305B\u3093**\u3002`decimalPlaces` \u3092\u8D85\u3048\u308B\u5C0F\u6570\u306F\u305D\u306E\u307E\u307E kintone \u3078\u6E21\u3057\u3001kintone \u304C `roundingMode` \u3067\u81EA\u52D5\u4E38\u3081\u3057\u307E\u3059\uFF08REST API\u30FBCSV \u8AAD\u307F\u8FBC\u307F\u30FB\u7DE8\u96C6\u753B\u9762\u30FB\u8A08\u7B97\u30D5\u30A3\u30FC\u30EB\u30C9\u3068\u540C\u3058\u6319\u52D5\uFF09\u3002`1/3` \u306A\u3069\u306E\u7B97\u8853\u7D50\u679C\u306B `ROUND` \u3092\u5F37\u5236\u3057\u307E\u305B\u3093\r\n- \u4E00\u822C\u8A2D\u5B9A\u306F\u540C\u3058\u5B9F\u884C\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30FB\u30A2\u30D7\u30EA\u3054\u3068\u306B\u6700\u59271\u56DE\u53D6\u5F97\u3057\u307E\u3059\u3002\u53D6\u5F97\u5931\u6557\u3001\u4E0D\u6B63\u30EC\u30B9\u30DD\u30F3\u30B9\u3001\u672A\u77E5\u306E\u4E38\u3081\u30E2\u30FC\u30C9\u3067\u306F\u65E2\u5B9A\u5024\u3092\u4EEE\u5B9A\u305B\u305A\u6587\u5168\u4F53\u3092fail-closed\u3057\u3001`ON ERROR SKIP` \u306E\u884C\u30A8\u30E9\u30FC\u306B\u306F\u5909\u63DB\u3057\u307E\u305B\u3093\r\n- \u65E2\u5B58 `ROUND` \u306E\u610F\u5473\u306F\u5909\u308F\u308A\u307E\u305B\u3093\u3002\u7B97\u8853\u3001\u96C6\u8A08\u3001\u6570\u5024\u95A2\u6570\u3001CASE\u3001CALC\u7531\u6765\u5024\u306E\u8A08\u7B97\u306F\u5F15\u304D\u7D9A\u304Dbinary64\u3067\u3059\r\n- \u5B8C\u5168\u306A\u5019\u88DC\u96C6\u5408\u304C\u5FC5\u8981\u306A\u305F\u3081\u3001`onLimit=truncate` / CLI `--on-limit truncate` / \u30D7\u30E9\u30B0\u30A4\u30F3\u306Etruncate\u8A2D\u5B9A\u306F\u7121\u8996\u3055\u308C\u3001\u5E38\u306Berror\u3068\u3057\u3066\u6271\u308F\u308C\u307E\u3059\r\n- \u30ED\u30FC\u30AB\u30EB\u691C\u8A3C\u306F\u901A\u5E38\u306E\u66F8\u304D\u8FBC\u307F\u7D4C\u8DEF\u3088\u308A\u53B3\u5BC6\u306A\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\u691C\u8A3C\u30A8\u30E9\u30FC\u306FkSQL\u304C\u691C\u51FA\u3057\u305FTier 0\u554F\u984C\u3067\u3042\u308A\u3001\u540C\u3058\u5024\u3092kintone API\u304C\u5FC5\u305A\u62D2\u5426\u3059\u308B\u3068\u3044\u3046\u4E88\u6E2C\u3067\u306F\u3042\u308A\u307E\u305B\u3093\r\n- \u691C\u8A3C\u901A\u904E\u306F\u66F8\u304D\u8FBC\u307F\u6210\u529F\u3092\u4FDD\u8A3C\u3057\u307E\u305B\u3093\u3002\u6A29\u9650\u3001\u7AF6\u5408\u3001\u30E6\u30FC\u30B6\u30FC\u5B9F\u5728\u6027\u3001\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u3068\u306E\u4E00\u610F\u5236\u7D04\u885D\u7A81\u306A\u3069API\u5B9F\u884C\u6642\u306E\u554F\u984C\u306F\u5BFE\u8C61\u5916\u3067\u3059\r\n- **`UPDATE` / `UPSERT`\uFF08update \u5206\u5C90\uFF09\u306E `VALIDATE ONLY` \u306F\u3001SET \u5BFE\u8C61\u5217\u3060\u3051\u3067\u306A\u304F\u3001\u66F4\u65B0\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u306E\u53D6\u5F97\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\u306B SET \u3092\u9069\u7528\u3057\u305F\u300Cpost-image\uFF08\u30EC\u30B3\u30FC\u30C9\u5168\u4F53\uFF09\u300D\u3092\u691C\u8A3C\u3057\u307E\u3059\uFF08v3.9.0\u30FBB43\uFF09\u3002** \u3053\u308C\u306B\u3088\u308A\u3001SET \u5BFE\u8C61\u5916\u306E\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u9805\u76EE\u3084**\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u884C\u306B\u6B8B\u308B\u65E2\u5B58\u9055\u53CD**\uFF08\u5FC5\u9808\u30FB\u6587\u5B57\u5217\u9577\u30FB\u6570\u5024\u7BC4\u56F2\u30FB\u9078\u629E\u80A2\u30FB\u6570\u5024\u7CBE\u5EA6\uFF09\u3082\u66F8\u304D\u8FBC\u307F\u524D\u306B\u691C\u51FA\u3057\u307E\u3059\u3002kintone \u306F PUT \u6642\u306B\u30EC\u30B3\u30FC\u30C9\u5168\u4F53\u3092\u518D\u691C\u8A3C\u3059\u308B\u305F\u3081\u3001\u3053\u306E\u691C\u8A3C\u306F\u672C\u5B9F\u884C\u6642\u306E `CB_VA01` \u3092\u524D\u5012\u3057\u3067\u6355\u6349\u3057\u307E\u3059\u3002\u5B50\u9055\u53CD\u306F `$err_subtable`\uFF08\u30C6\u30FC\u30D6\u30EB\u30B3\u30FC\u30C9\uFF09\u30FB`$err_subrow`\uFF081-based \u884C\u5E8F\u6570\uFF09\u30FB`$err_subrow_id`\uFF08\u6C38\u7D9A\u884C ID\uFF1D\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u306E `_rid`\uFF09\u3067\u4F4D\u7F6E\u3092\u793A\u3057\u307E\u3059\u3002\u30D7\u30EC\u30FC\u30F3\u306A `UPDATE`/`UPSERT` \u5B9F\u884C\uFF08`VALIDATE ONLY`/`ON ERROR SKIP` \u306A\u3057\uFF09\u306E\u53D6\u5F97\u6319\u52D5\u306F\u5909\u308F\u308A\u307E\u305B\u3093\r\n- \u3053\u306E\u691C\u8A3C\u306E\u305F\u3081\u3001`UPDATE`/`UPSERT` \u306E `VALIDATE ONLY` \u306F\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u306E\u5B8C\u5168\u306A\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\uFF08`$id`\uFF0B\u691C\u8A3C\u5BFE\u8C61\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\uFF0B\u5168\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\uFF09\u3092\u53D6\u5F97\u3057\u307E\u3059\u3002`UPDATE` \u306F\u65E2\u5B58 GET \u306E\u53D6\u5F97\u5217\u3092\u62E1\u5F35\u3057\u3001`UPSERT` \u306F\u7167\u5408\u5F8C\u306B\u66F4\u65B0\u5BFE\u8C61 ID \u3092100\u4EF6\u305A\u3064\u307E\u3068\u3081\u3066\u8FFD\u52A0\u53D6\u5F97\u3057\u307E\u3059\uFF08\u5BFE\u8C611\u4EF6\u3054\u3068\u306E\u8FFD\u52A0 GET \u306F\u884C\u3044\u307E\u305B\u3093\uFF09\r\n\r\n## 17.2 ON ERROR SKIP\uFF08\u4E8B\u524D\u691C\u8A3C\u30A8\u30E9\u30FC\u884C\u306E\u9694\u96E2\uFF09\r\n\r\n\u8907\u6587\u30D0\u30C3\u30C1\u5185\u306E\u89AA\u30EC\u30B3\u30FC\u30C9 `INSERT` / `UPSERT` / `UPDATE` \u306B `ON ERROR SKIP INTO #err` \u3092\u4ED8\u3051\u308B\u3068\u3001`VALIDATE ONLY` \u3068\u540C\u3058Tier 0\u691C\u8A3C\u3067\u4E0D\u6B63\u306B\u306A\u3063\u305F\u884C\u3092 `#err` \u3078\u9694\u96E2\u3057\u3001\u5408\u683C\u884C\u3060\u3051\u3092\u66F8\u304D\u8FBC\u307F\u307E\u3059\u3002\u66F8\u304D\u8FBC\u307F\u3092\u884C\u3046\u305F\u3081\u3001MCP\u3067\u306F `ksql_mutate` \u3068DML\u627F\u8A8D\u3001CLI\u3067\u306F `--allow-dml` \u304C\u5FC5\u8981\u3067\u3059\u3002**`UPDATE` / `UPSERT`\uFF08update \u5206\u5C90\uFF09\u3067\u306F \xA717.1 \u306E post-image \u691C\u8A3C\u306B\u3088\u308A\u3001\u66F4\u65B0\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u3092\u542B\u3080\u65E2\u5B58\u9055\u53CD\u3092\u6301\u3064\u89AA\u3082\u9694\u96E2\u5BFE\u8C61\u306B\u306A\u308A\u307E\u3059\uFF08v3.9.0\u30FBB43\uFF09\u3002** \u3053\u308C\u306B\u3088\u308A\u3001\u65E2\u5B58\u9055\u53CD\u30EC\u30B3\u30FC\u30C91\u4EF6\u304C\u540C\u4E00\u30C1\u30E3\u30F3\u30AF\u306E\u5408\u683C\u884C\u307E\u3067\u5DFB\u304D\u6DFB\u3048\u306B\u3057\u3066 `CB_VA01` \u3067\u5931\u6557\u3059\u308B\u4E8B\u614B\u3092\u9632\u304E\u3001\u5408\u683C\u89AA\u3060\u3051\u3092\u78BA\u5B9F\u306B\u66F8\u304D\u8FBC\u307F\u307E\u3059\u3002\r\n\r\n```sql\r\nINSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D FROM #source\r\nON ERROR SKIP INTO #err REJECT LIMIT 100;\r\n\r\nSELECT * FROM #err;\r\n```\r\n\r\n- `REJECT LIMIT n` \u306F\u9694\u96E2\u3055\u308C\u305F\u30E6\u30CB\u30FC\u30AF\u5165\u529B\u884C\u6570\u3078\u9069\u7528\u3057\u307E\u3059\u3002n\u884C\u307E\u3067\u306F\u8A31\u5BB9\u3057\u3001n+1\u884C\u4EE5\u4E0A\u306A\u3089\u5168\u5019\u88DC\u306E\u691C\u8A3C\u5B8C\u4E86\u5F8C\u306B\u66F8\u304D\u8FBC\u307F\u30BC\u30ED\u3067\u505C\u6B62\u3057\u307E\u3059\u3002\u7701\u7565\u6642\u306F\u7121\u5236\u9650\u3067\u3059\r\n- \u8D85\u904E\u6587\u306F `RejectLimitExceededError` \u306B\u306A\u308A\u307E\u3059\u304C\u3001\u5168\u8A3A\u65AD\u884C\u306F\u5FDC\u7B54\u306E\u7D50\u679C\u30BB\u30C3\u30C8\u306B\u542B\u307E\u308C\u307E\u3059\u3002\u5F8C\u7D9A\u6587\u306Ffail-fast\u3067skip\u3055\u308C\u308B\u305F\u3081\u3001\u8D85\u904E\u6642\u306F\u5F8C\u7D9ASQL\u304B\u3089 `#err` \u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\r\n- `ON ERROR SKIP` \u306F `INTO #err` \u5FC5\u9808\u306E\u30D0\u30C3\u30C1\u5C02\u7528\u69CB\u6587\u3067\u3059\u3002\u5358\u6587\u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\r\n- \u7D50\u679C\u306B\u306F\u65E2\u5B58\u306Eoperation\u5225\u4EF6\u6570\u306B\u52A0\u3048\u3066 `affectedRows` / `skippedRows` / `rejectLimit` / `errTable` \u304C\u542B\u307E\u308C\u307E\u3059\r\n- `dmlMaxRows` \u3068 `dmlTotalMaxRows` \u306F\u9694\u96E2\u5F8C\u306B\u5B9F\u969B\u306B\u66F8\u304D\u8FBC\u3080\u884C\u6570\u3078\u9069\u7528\u3055\u308C\u307E\u3059\u3002\u30BD\u30FC\u30B9\u53D6\u5F97\u306F\u901A\u5E38\u306E `maxRecords` \u3067\u5236\u5FA1\u3055\u308C\u307E\u3059\r\n- \u7D44\u307F\u8FBC\u307F\u5236\u7D04\uFF08\u5FC5\u9808\u30FB\u6587\u5B57\u5217\u9577\u30FB\u6570\u5024\u7BC4\u56F2\u30FB\u9078\u629E\u80A2\u30FB\u6570\u5024\u7CBE\u5EA6\uFF09\u306E\u65E2\u5B58\u9055\u53CD\u306F\u3001update \u5206\u5C90\u3067\u306F post-image \u691C\u8A3C\u3067\u4E8B\u524D\u306B\u691C\u51FA\u30FB\u9694\u96E2\u3055\u308C\u307E\u3059\uFF08v3.9.0\u30FBB43\uFF09\u3002\u4E00\u65B9\u3001kintone API\u304C\u66F8\u304D\u8FBC\u307F\u6642\u306B\u8FD4\u3059\u6A29\u9650\u30FB\u7AF6\u5408\u30FB\u4E00\u610F\u5236\u7D04\u30FB\u30E6\u30FC\u30B6\u30FC\u5B9F\u5728\u6027\u306A\u3069\u306E\u5B9F\u884C\u6642\u30A8\u30E9\u30FC\u306F\u9694\u96E2\u305B\u305A\u3001\u5F93\u6765\u3069\u304A\u308Afail-fast\u3067\u3059\r\n\r\n---\r\n\r\n## 17.3 CHECK\uFF08\u30AB\u30B9\u30BF\u30E0\u30C1\u30A7\u30C3\u30AF\u30FBv3.4.0\uFF09\r\n\r\n`INSERT` / `UPSERT` / `UPDATE` \u306E\u30BD\u30FC\u30B9\u306E\u5F8C\u3001\u51E6\u5206\u7BC0\uFF08`VALIDATE ONLY` / `ON ERROR SKIP`\uFF09\u306E\u524D\u306B `CHECK` \u30D6\u30ED\u30C3\u30AF\u3092\u7F6E\u304F\u3068\u3001\u30E6\u30FC\u30B6\u30FC\u5B9A\u7FA9\u306E\u884C\u30EC\u30D9\u30EB\u696D\u52D9\u30EB\u30FC\u30EB\u3067\u4E0D\u6B63\u884C\u3092 `#err`\uFF08`$err_code = ERR_CHECK`\uFF09\u3078\u9694\u96E2\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\nINSERT INTO APP123 (\u6570\u50241, \u6570\u50242, \u6570\u50243)\r\nSELECT \u6570\u50241, \u6570\u50242, \u6570\u50243 FROM APP999\r\nCHECK\r\n WHEN \u6570\u50241 IS NULL THEN '\u6570\u50241 \u672A\u5165\u529B\u30A8\u30E9\u30FC'\r\n WHEN \u6570\u50241 > \u6570\u50242 THEN '\u6570\u50241=' || \u6570\u50241 || ' \u304C \u6570\u50242=' || \u6570\u50242 || ' \u3092\u8D85\u904E'\r\nCHECK\r\n WHEN \u6570\u50243 > 100 THEN CONCAT('\u6570\u50243 \u304C\u4E0A\u9650\u8D85\u904E: ', \u6570\u50243)\r\nON ERROR SKIP INTO #err;\r\n```\r\n\r\n- **\u30B0\u30EB\u30FC\u30D7\uFF1D\u5148\u52DD\u3061**\uFF1A1 \u3064\u306E `CHECK` \u30D6\u30ED\u30C3\u30AF\u5185\u306F\u4E0A\u304B\u3089\u8A55\u4FA1\u3057\u3001\u6700\u521D\u306B\u8A72\u5F53\u3057\u305F `WHEN` \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u3060\u3051\u3092 1 \u4EF6\u51FA\u3057\u307E\u3059\u3002`CHECK` \u30D6\u30ED\u30C3\u30AF\u3092\u8907\u6570\u4E26\u3079\u308B\u3068\u4E92\u3044\u306B\u72EC\u7ACB\u306B\u8A55\u4FA1\u3057\u307E\u3059\uFF08\u95A2\u9023\u30C1\u30A7\u30C3\u30AF\u306F\u540C\u3058\u30D6\u30ED\u30C3\u30AF\uFF1D\u6700\u521D\u306E\u30A8\u30E9\u30FC\u306E\u307F\u3001\u7121\u95A2\u4FC2\u30C1\u30A7\u30C3\u30AF\u306F\u5225\u30D6\u30ED\u30C3\u30AF\uFF1D\u305D\u308C\u305E\u308C\uFF09\u3002\r\n- **\u53C2\u7167\u306F\u8AAD\u307F\u53D6\u308A\u884C**\uFF1A\r\n - `INSERT` / `UPSERT \u2026 SELECT` \u306F\u5143 SELECT \u306E\u51FA\u529B\u5217\uFF08\u5225\u540D\u53EF\uFF09\u3002**\u5148\u982D N \u5217\u304C\u66F8\u304D\u8FBC\u307F\u5BFE\u8C61\u3001\u6B8B\u308A\u306E\u672B\u5C3E\u5217\u306F CHECK \u5C02\u7528**\uFF08`CHECK` \u3092\u4ED8\u3051\u308B\u3068\u304D SELECT \u51FA\u529B\u540D\u306F\u4E00\u610F\u306B\u3059\u308B\uFF09\u3002\r\n - `\u2026 VALUES` \u306F\u633F\u5165\u5217\u3002\r\n - `UPDATE` \u306F**\u66F4\u65B0\u524D\u306E\u65E2\u5B58\u5024**\uFF08\u66F8\u304D\u8FBC\u3080\u65B0\u5024\u3092\u691C\u67FB\u3057\u305F\u3044\u3068\u304D\u306F SET \u5F0F\u3092\u66F8\u304F\uFF1A`SET \u6570\u91CF = \u6570\u91CF - \u51FA\u5EAB\u6570` \u306B\u5BFE\u3057 `WHEN \u6570\u91CF - \u51FA\u5EAB\u6570 < 0`\uFF09\u3002\r\n - `UPDATE \u2026 FROM` \u306F `APP.\u5217`\uFF1D\u66F4\u65B0\u524D\u30BF\u30FC\u30B2\u30C3\u30C8\u30FB`<\u30BD\u30FC\u30B9\u5225\u540D>.\u5217`\uFF1D\u30BD\u30FC\u30B9\u65B0\u5024\u3067\u8B58\u5225\uFF08`WHEN s.\u91D1\u984D < APP100.\u91D1\u984D THEN '\u6E1B\u984D\u4E0D\u53EF'`\uFF09\u3002\u30BD\u30FC\u30B9\u5217\u3092\u4FEE\u98FE\u306A\u3057\u3067\u53C2\u7167\u3059\u308B\u3068\u30A8\u30E9\u30FC\u3002\r\n- \u30E1\u30C3\u30BB\u30FC\u30B8\u306F `||` / `CONCAT` \u3067\u30D5\u30A3\u30FC\u30EB\u30C9\u3084 `@var` \u3092\u88DC\u9593\u3067\u304D\u307E\u3059\u3002**\u6761\u4EF6\uFF08`WHEN`\uFF09\u3067\u306F `||` \u306F\u4F7F\u3048\u307E\u305B\u3093**\uFF08`CONCAT` \u3092\u4F7F\u3046\uFF09\u3002\r\n- \u51E6\u5206\uFF1A`ON ERROR SKIP INTO #err` \u306F\u8A72\u5F53\u884C\u3092\u9694\u96E2\u3057\u3066\u6B8B\u308A\u3092\u66F8\u304D\u8FBC\u307F\u3001`VALIDATE ONLY` \u306F\u66F8\u304B\u305A\u306B\u5831\u544A\u3001\u51E6\u5206\u7BC0\u306A\u3057\u306E\u7D20 DML \u306F\u66F8\u304D\u8FBC\u307F\u524D\u306B\u505C\u6B62\u3057\u307E\u3059\u3002\u7D44\u307F\u8FBC\u307F\u691C\u8A3C\uFF08\u5FC5\u9808\u30FB\u578B\u30FB\u7BC4\u56F2\u30FB\u6841\uFF09\u3068\u306F\u72EC\u7ACB\u306B\u8A55\u4FA1\u3057\u3001`#err` \u306F\u7D44\u307F\u8FBC\u307F\u30A8\u30E9\u30FC \u2192 \u30AB\u30B9\u30BF\u30E0\u30A8\u30E9\u30FC\u306E\u9806\u3067\u3059\u3002\u6BD4\u8F03\u975E\u5BFE\u5FDC\u306E\u8907\u5408\u578B\u3092\u6761\u4EF6\u306B\u4F7F\u3046\u7B49\u306E\u8A55\u4FA1\u4E0D\u80FD\u306F\u6587\u5168\u4F53\u30A8\u30E9\u30FC\uFF08\u884C\u9694\u96E2\u3057\u307E\u305B\u3093\uFF09\u3002\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB DML \u306B\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002`CHECK` \u306F `CHECK WHEN` \u306E\u4E26\u3073\u306E\u3068\u304D\u3060\u3051\u30AD\u30FC\u30EF\u30FC\u30C9\u306B\u306A\u308A\u307E\u3059\uFF08\u540C\u540D\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\uFF09\u3002\r\n\r\n## 17.4 VALIDATE\uFF08\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u306E\u8AAD\u307F\u53D6\u308A\u76E3\u67FB\uFF09\r\n\r\n\u5148\u982D\u306E `VALIDATE` \u6587\u306F\u3001\u4FDD\u5B58\u6E08\u307F\u30EC\u30B3\u30FC\u30C9\u3078\u30D5\u30A9\u30FC\u30E0\u306E\u7D44\u307F\u8FBC\u307F\u5236\u7D04\u3068\u4EFB\u610F\u306E `CHECK` \u3092\u9069\u7528\u3059\u308B read-only \u6587\u3067\u3059\u3002DML \u672B\u5C3E\u306E `VALIDATE ONLY` \u3068\u306F\u5225\u6587\u3067\u3001kintone \u306E POST / PUT / DELETE API \u306F\u547C\u3073\u307E\u305B\u3093\u3002\r\n\r\n```sql\r\nVALIDATE APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u660E\u7D30(\u6570\u91CF, \u5358\u4FA1))\r\nWHERE \u4F5C\u6210\u65E5\u6642 >= '2026-01-01'\r\nCHECK WHEN \u91D1\u984D < 0 THEN '\u91D1\u984D\u304C\u8CA0\u3067\u3059';\r\n\r\nVALIDATE APP100 INTO #err;\r\nSELECT $id, $err_field, $err_code, $err_message, $err_value,\r\n $err_subtable, $err_subrow, $err_subrow_id\r\nFROM #err;\r\n\r\n-- \u5927\u91CF\u9055\u53CD\u306F\u8A73\u7D30\u884C\u3092\u4F5C\u3089\u305A\u89AA\xD7\u30C6\u30FC\u30D6\u30EB\xD7\u30D5\u30A3\u30FC\u30EB\u30C9\xD7\u30B3\u30FC\u30C9\u3067\u96C6\u7D04\r\nVALIDATE APP100 SUMMARY INTO #summary;\r\n```\r\n\r\n- `(fields)` \u7701\u7565\u6642\u306F\u3001\u5236\u7D04\u3092\u6301\u3064\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\uFF0F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9\u3068\u3001\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\uFF0F\u5B50\u306E\u5168 `NUMBER` \u304C\u5BFE\u8C61\u3067\u3059\u3002\u30C6\u30FC\u30D6\u30EB\u30B3\u30FC\u30C9\u5358\u72EC\u306F\u305D\u306E\u30C6\u30FC\u30D6\u30EB\u306E\u76E3\u67FB\u53EF\u80FD\u306A\u5B50\u3059\u3079\u3066\u3001`\u30C6\u30FC\u30D6\u30EB(\u5B501, \u5B502)` \u306F\u6307\u5B9A\u3057\u305F\u5B50\u3060\u3051\u3092\u9078\u3073\u307E\u3059\u3002\u88F8\u306E\u5B50\u30B3\u30FC\u30C9\u3001\u672A\u77E5\u30FB\u6240\u5C5E\u9055\u3044\u30FB\u91CD\u8907\u30FB\u76E3\u67FB\u5BFE\u8C61\u5916\u306F\u53D6\u5F97\u524D\u306B\u62D2\u5426\u3057\u307E\u3059\r\n- \u8A73\u7D30\u51FA\u529B\u306F\u56FA\u5B9A9\u5217 `$id`, `$err_field`, `$err_code`, `$err_message`, `$err_value`, `$err_subtable`, `$err_subrow`, `$err_subrow_id`, `$err_count` \u3067\u3059\u3002\u540C\u4E00\u30EC\u30B3\u30FC\u30C9\u306E\u9055\u53CD\u3092\u88C5\u98FE\u524D\u306E\u5143 message \u3092\u542B\u3080 `($id, $err_subtable, $err_field, $err_code, $err_message)` \u3067\u96C6\u7D04\u3057\u3001`$err_count` \u306B\u4EF6\u6570\u3092\u6587\u5B57\u5217\u5316\u3057\u3066\u683C\u7D0D\u3057\u307E\u3059\u3002\u7570\u306A\u308B\u5143 message \u306F\u5225\u884C\u3067\u3059\u3002\u51FA\u529B\u306F\u5148\u982D\u51FA\u73FE\u9806\u3067\u3001`$err_value` \u306F\u30B0\u30EB\u30FC\u30D7\u5148\u982D\u306E\u5024\u3092\u4FDD\u6301\u3057\u307E\u3059\u3002\u5B50\u9055\u53CD\u306E `$err_subrow` \u306F\u5168\u8A72\u5F53\u884C\u306E1-based\u8868\u793A\u5E8F\u6570\u3001`$err_subrow_id` \u306F\u540C\u9806\u306E\u5168\u6C38\u7D9A\u884CID\uFF08\u5404\u8981\u7D20\u304C\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u306E `_rid` \u3068\u540C\u5024\uFF09\u3092\u3001\u305D\u308C\u305E\u308C\u30AB\u30F3\u30DE\u533A\u5207\u308A\u30FB\u5207\u308A\u6368\u3066\u306A\u3057\u3067\u683C\u7D0D\u3057\u307E\u3059\uFF08\u4F8B: `\"1,2\"` / `\"r10,r20\"`\uFF09\u3002\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u9055\u53CD\u304B\u3064 `$err_count >= 2` \u306E\u51FA\u529B message \u306B\u306F\u96C6\u7D04\u5F8C\u306B `\uFF08{count}\u884C: {subrow\u30EA\u30B9\u30C8}\uFF09` \u3092\u4ED8\u3051\u307E\u3059\uFF08\u4F8B: `\u6587\u5B57\u5217T2 \u306F 3 \u6587\u5B57\u4EE5\u4E0A\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF082\u884C: 1,2\uFF09`\uFF09\u3002\u30EA\u30B9\u30C8\u306F `$err_subrow` \u3068\u540C\u4E00\u3067\u3001\u5148\u982D\u51FA\u73FE\u9806\u30FB\u5207\u308A\u6368\u3066\u306A\u3057\u3067\u3059\u3002`$err_count=1` \u306E\u5B50\u9055\u53CD\u3001\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u9055\u53CD\u3001`CHECK` \u9055\u53CD\u306E message \u306F\u5F93\u6765\u3069\u304A\u308A\u3067\u3059\u3002`INTO #err` \u306B\u3082\u88C5\u98FE\u6E08\u307F message \u3092\u683C\u7D0D\u3057\u307E\u3059\u3002\u578B\u30E1\u30BF\u306F `$err_subrow=string`\u3001`$err_count=number` \u3067\u3059\u3002\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\uFF0F`CHECK` \u306E\u30ED\u30B1\u30FC\u30BF3\u5217\u306F\u7A7A\u3067\u3001\u901A\u5E38 `$err_count=1` \u3067\u3059\u30020\u884C\u30C6\u30FC\u30D6\u30EB\u3067\u306F\u5B50\u306E\u5FC5\u9808\u9055\u53CD\u306F\u767A\u706B\u3057\u307E\u305B\u3093\r\n- `SUMMARY` \u306F `(fields)` \u5F8C\u30FB`WHERE` \u524D\u306B\u7F6E\u304F soft keyword \u3067\u3059\u3002\u8A73\u7D30\u884C\u3092\u751F\u6210\u305B\u305A\u3001\u56FA\u5B9A5\u5217 `$id`, `$err_subtable`, `$err_field`, `$err_code`, `$err_count` \u3078\u76F4\u63A5\u96C6\u7D04\u3057\u307E\u3059\u3002SUMMARY \u306F\u30EC\u30B3\u30FC\u30C9\u6A2A\u65AD\u306E\u898F\u6A21\u628A\u63E1\u3001\u8A73\u7D309\u5217\u306F message \u5225\u306E\u30EC\u30B3\u30FC\u30C9\u5185\u8A33\u3068\u5168\u8A72\u5F53\u884C\u30ED\u30B1\u30FC\u30BF\u30EA\u30B9\u30C8\u306B\u4F7F\u3044\u307E\u3059\r\n- \u8A73\u7D30\uFF0F`SUMMARY` \u306E\u3069\u3061\u3089\u3082\u3001\u7D50\u679C\u30E1\u30BF\u30C7\u30FC\u30BF `validateStats` \u306B\u96C6\u7D04\u524D\u306E\u7D71\u8A08\u3092\u8FD4\u3057\u307E\u3059\u3002`errorRecords` \u306F\u9055\u53CD\u30921\u4EF6\u4EE5\u4E0A\u6301\u3064 distinct `$id` \u6570\u3001`errorCount` \u306F\u96C6\u7D04\u524D\u306E\u9055\u53CD\u7DCF\u6570\u3067\u3001\u7D50\u679C\u884C\u306E `$err_count` \u5408\u8A08\u3068\u4E00\u81F4\u3057\u307E\u3059\u3002\u9055\u53CD0\u4EF6\u3067\u3082 `{ \"errorRecords\": 0, \"errorCount\": 0 }` \u3092\u8FD4\u3057\u307E\u3059\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u306F `\u30A8\u30E9\u30FC {errorRecords} \u30EC\u30B3\u30FC\u30C9 / {errorCount} \u4EF6\uFF08\u8868\u793A {rowCount} \u884C\uFF09`\u3001CLI \u306E table\uFF0Fmarkdown \u306F\u672B\u5C3E\u30B5\u30DE\u30EA\u306B `errorRecords=\u2026 errorCount=\u2026` \u3092\u8868\u793A\u3057\u3001JSON\uFF0FMCP \u306F `validateStats` \u3092\u542B\u3081\u307E\u3059\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u306E `INTO #err` \u306F\u30C6\u30FC\u30D6\u30EB\u306E\u4EE3\u308F\u308A\u306B `VALIDATE: \u30A8\u30E9\u30FC {errorRecords} \u30EC\u30B3\u30FC\u30C9 / {errorCount} \u4EF6\uFF08#err \u3078 {rowCount} \u884C\uFF09` \u3092\u6587\u4F4D\u7F6E\u3078\u8868\u793A\u3057\u307E\u3059\u3002`INTO #err` \u3092\u4F7F\u3046\u30D0\u30C3\u30C1\u3067\u3082\u7D71\u8A08\u306F VALIDATE \u6587\u81EA\u8EAB\u306E\u7D50\u679C\u3060\u3051\u306B\u4ED8\u304D\u3001\u5F8C\u7D9A\u306E\u6C4E\u7528 `SELECT` \u306B\u306F\u5F15\u304D\u7D99\u304E\u307E\u305B\u3093\r\n- `INTO #err` \u306F\u8907\u6587\u30D0\u30C3\u30C1\u5C02\u7528\u3067\u3059\u3002\u8A73\u7D309\u5217\u3068 SUMMARY 5\u5217\u306F\u5225\u30B9\u30AD\u30FC\u30DE\u3067\u3001\u540C\u540D\u4E00\u6642\u8868\u3078\u306E\u6DF7\u5728\u8FFD\u8A18\u306F\u89E3\u6790\u6642\u306B\u62D2\u5426\u3057\u307E\u3059\u3002`tempTableMaxRows` \u306F\u3069\u3061\u3089\u3082\u96C6\u7D04\u5F8C\u884C\u6570\u3078\u9069\u7528\u3057\u3001\u8D85\u904E\u6642\u306F\u90E8\u5206\u7D50\u679C\u3092\u6B8B\u3055\u305A\u30A8\u30E9\u30FC\u306B\u3057\u307E\u3059\r\n- `WHERE` \u306F\u901A\u5E38\u6BD4\u8F03\u3001`BETWEEN`, \u30EA\u30C6\u30E9\u30EB `IN`, `IS NULL`, `LIKE` \u3092\u4F7F\u3048\u307E\u3059\u3002`KLIKE`, \u30B5\u30D6\u30AF\u30A8\u30EA, \u4FEE\u98FE\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3001\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u53C2\u7167\u306F\u4F7F\u3048\u307E\u305B\u3093\u3002`CHECK` \u3082\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u53C2\u7167\u3060\u3051\u3067\u3059\u3002\u5B89\u5168\u306A\u6761\u4EF6\u3060\u3051\u3092\u53D6\u5F97\u6642\u306B\u62BC\u3057\u4E0B\u3052\u3001\u53D6\u5F97\u5F8C\u306B\u5143\u306E\u6761\u4EF6\u5168\u4F53\u3092\u518D\u8A55\u4FA1\u3057\u307E\u3059\r\n- \u5B8C\u5168\u306A\u76E3\u67FB\u96C6\u5408\u304C\u5FC5\u8981\u306A\u305F\u3081\u3001\u5168 surface \u3067 `onLimit=truncate` \u3092\u7121\u52B9\u5316\u3057\u3066 error \u306B\u3057\u307E\u3059\u3002\u53D6\u5F97\u306F\u901A\u5E38 records API \u306E offset + `$id` keyset paging \u3067\u3001Cursor API \u306F\u4F7F\u3044\u307E\u305B\u3093\r\n- `EXPLAIN VALIDATE` \u306F\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u3068\u3001NUMBER \u5BFE\u8C61\u304C\u3042\u308B\u5834\u5408\u306E\u6570\u5024\u7CBE\u5EA6\u3060\u3051\u3092\u8AAD\u307F\u307E\u3059\u3002\u30EC\u30B3\u30FC\u30C9 API / mutation API \u306F\u547C\u3070\u305A\u3001\u9055\u53CD\u4EF6\u6570\u3082\u7B97\u51FA\u3057\u307E\u305B\u3093", uri: "ksql://language-reference/17-upsert" }, "18-delete": { heading: "18. DELETE", text: "## 18. DELETE\r\n\r\n```sql\r\nDELETE FROM APP100\r\nWHERE \u6761\u4EF6\r\n```\r\n\r\n```sql\r\nDELETE FROM APP100\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u30AD\u30E3\u30F3\u30BB\u30EB'\r\n\r\nDELETE FROM APP100\r\nWHERE \u4F5C\u6210\u65E5\u6642 < '2020-01-01'\r\n```\r\n\r\n> **WHERE \u53E5\u306F\u5FC5\u9808\u3067\u3059\u3002** \u5168\u4EF6\u524A\u9664\u3092\u9632\u3050\u305F\u3081\u3001WHERE \u306A\u3057\u306E DELETE \u306F\u69CB\u6587\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002 \r\n> \u6CE8: CLI \u306B\u306F `--allow-without-where` \u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u3059\u304C\u3001\u73FE\u884C\u5B9F\u88C5\u3067\u306F UPDATE/DELETE \u306E\u6587\u6CD5\u4E0A WHERE \u304C\u5FC5\u9808\u3067\u3059\u3002\r\n\r\n> **\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0:** \u5B9F\u884C\u524D\u306B\u5BFE\u8C61\u4EF6\u6570\u3092\u8868\u793A\u3057\u3066\u78BA\u8A8D\u3092\u6C42\u3081\u307E\u3059\u3002 \r\n> \u30AD\u30E3\u30F3\u30BB\u30EB\u3059\u308B\u3068\u524A\u9664\u306F\u884C\u308F\u308C\u307E\u305B\u3093\u3002\r\n\r\n> **CLI \u62E1\u5F35\u306E\u5236\u7D04:** `DELETE` \u3067\u306E `APP@profile` \u6307\u5B9A\u306F\u672A\u5BFE\u5FDC\u3067\u3059\u3002 \r\n> \u4F8B: `DELETE FROM APP100@guest WHERE ...` \u306F \r\n> `ArgumentError: @profile is not supported for DELETE yet.` \u3067\u7D42\u4E86\u3057\u307E\u3059\u3002\r\n\r\n---\r\n\r\n## 18.1 IMPORT\uFF08\u30D5\u30A1\u30A4\u30EB\u53D6\u8FBC\u30FBv3.6.0\uFF09\r\n\r\nCSV / JSON \u30D5\u30A1\u30A4\u30EB\u3092\u3001**\u5C04\u5F71\u30FB\u691C\u8A3C\u30FB\u4E0D\u826F\u884C\u9694\u96E2\u30FBcli-kintone \u4E92\u63DB**\u3092\u5099\u3048\u3066 kintone \u30A2\u30D7\u30EA\u3078\u4E00\u62EC\u767B\u9332\uFF0F\u66F4\u65B0\u3059\u308B\u81EA\u5DF1\u5B8C\u7D50\u30B9\u30C6\u30FC\u30C8\u30E1\u30F3\u30C8\u3067\u3059\u3002\u65E2\u5B9A\u3067\u306F\u7121\u52B9\uFF08capability gate off\uFF09\u3067\u3001**\u9762\u304C\u30BD\u30FC\u30B9\u3092\u540D\u524D\u3067\u4F9B\u7D66\u3057\u305F\u3068\u304D\u3060\u3051\u6709\u52B9**\u306B\u306A\u308A\u307E\u3059\u3002SQL \u672C\u6587\u306B\u30D5\u30A1\u30A4\u30EB\u30D1\u30B9\u306F\u66F8\u304D\u307E\u305B\u3093\uFF08\u30A4\u30F3\u30B8\u30A7\u30AF\u30B7\u30E7\u30F3\u9632\u6B62\u30FB1 \u30BD\u30FC\u30B9\u6700\u5927 10 MiB\uFF09\u3002\r\n\r\n### \u69CB\u6587\r\n\r\n```\r\nIMPORT [UPDATE] INTO APP ( <\u53D6\u8FBC\u5148> )\r\n FROM CSV|JSON <\u30BD\u30FC\u30B9\u540D>\r\n [ENCODING UTF8|SJIS] -- CSV \u306E\u307F\uFF08\u65E2\u5B9A UTF8\uFF09\r\n [NO HEADER [COLUMNS (col, ...)]] -- CSV \u306E\u307F\r\n [SELECT <\u5F0F>, ...] -- CSV \u306E\u307F\uFF08\u4F4D\u7F6E\u6307\u5B9A\u306E\u4EE3\u308F\u308A\u306B\u5C04\u5F71\uFF09\r\n [BY NAME [IGNORE UNKNOWN COLUMNS]] -- CSV \u306E\u307F\uFF08\u30D8\u30C3\u30C0\uFF1D\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\uFF09\r\n [MATCH RECORD NUMBER SOURCE <\u30D8\u30C3\u30C0>] -- IMPORT UPDATE \u5FC5\u9808\r\n [ON DUPLICATE (\u30AD\u30FC, ...)] -- UPSERT\r\n [REPLACE SUBTABLES (\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB, ...)] -- CSV \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306E\u307F\r\n [CHECK WHEN ... THEN ...] -- \xA717.3\r\n [VALIDATE ONLY [INTO #err] | ON ERROR SKIP INTO #err [REJECT LIMIT n]] -- \xA717.1 / \xA717.2\r\n```\r\n\r\n`<\u53D6\u8FBC\u5148>` \u306F `\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9`\u3001\u307E\u305F\u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB `\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u30B3\u30FC\u30C9(\u5B501, \u5B502) [ROW ID SOURCE <\u30D8\u30C3\u30C0>]`\uFF08`ROW ID SOURCE` \u306F\u5B50\u5217\u30EA\u30B9\u30C8\u306E\u9589\u3058\u62EC\u5F27\u306E**\u5F8C**\uFF09\u3002\r\n\r\n### \u30BD\u30FC\u30B9\u306E\u4F9B\u7D66\uFF08\u9762\u3054\u3068\uFF09\r\n\r\n| \u9762 | \u4F9B\u7D66\u65B9\u6CD5 |\r\n|---|---|\r\n| CLI | `--import-csv =` / `--import-json =`\uFF08\u53CD\u5FA9\u53EF\u30FB\u6307\u5B9A\u3067 gate ON\uFF09 |\r\n| MCP | \u5F15\u6570 `importSources: [{ name, text \\| base64, encoding? }]`\uFF08inline\u30FB\u30D1\u30B9\u4E0D\u53EF\u30FB\u6307\u5B9A\u3067 gate ON\uFF09 |\r\n| \u30D7\u30E9\u30B0\u30A4\u30F3 | \u30D8\u30C3\u30C0\u30FC\u306E\u300C\u30D5\u30A1\u30A4\u30EB\u3092\u9078\u629E\u300D\uFF08\u30BD\u30FC\u30B9\u540D\uFF1D\u62E1\u5F35\u5B50\u3092\u9664\u53BB\u3057\u3001\u8B58\u5225\u5B50\u306B\u4F7F\u3048\u306A\u3044\u6587\u5B57\u3092 `_` \u306B\u6B63\u898F\u5316\u3002`sales.csv` \u2192 `sales`\u3001`sales 2026.csv` \u2192 `sales_2026`\uFF09 |\r\n\r\n### CSV \u306E\u53D6\u8FBC\r\n\r\n\u5217\u306E\u5BFE\u5FDC\u306F 3 \u901A\u308A:\r\n\r\n- **\u4F4D\u7F6E\u6307\u5B9A**\uFF08\u65E2\u5B9A\uFF09: CSV \u5217\u3092 `INTO (...)` \u306E\u9806\u3067\u5BFE\u5FDC\u3002\r\n- **\u5C04\u5F71 `SELECT`**: \u53D6\u8FBC\u524D\u306B\u5F0F\u5909\u63DB\uFF08`CAST` / \u95A2\u6570 / `||` / `@var`\uFF09\u3002`FROM` / `JOIN` / `WHERE` / `GROUP BY` / `ORDER BY` / `LIMIT` / \u30B5\u30D6\u30AF\u30A8\u30EA / \u4FEE\u98FE\u53C2\u7167\u306F\u4E0D\u53EF\uFF08\u7D14\u7C8B\u306A\u5F0F\u306E\u4E26\u3073\u306E\u307F\u30FB\u5217\u6570\u306F\u53D6\u8FBC\u5148\u3068\u4E00\u81F4\uFF09\u3002\r\n- **`BY NAME`**: \u30D8\u30C3\u30C0\u884C\u3092\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u3068\u3057\u3066\u5BFE\u5FDC\uFF08cli-kintone \u4E92\u63DB\uFF09\u3002\r\n\r\n```sql\r\n-- \u4F4D\u7F6E\u6307\u5B9A + UPSERT\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nFROM CSV sales\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9);\r\n\r\n-- \u5C04\u5F71\u3067\u6570\u5024\u5316\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nFROM CSV sales\r\nSELECT code, CAST(amount AS NUMBER) AS \u91D1\u984D;\r\n\r\n-- \u30D8\u30C3\u30C0\u7121\u3057\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nFROM CSV sales NO HEADER COLUMNS (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D);\r\n```\r\n\r\n- CSV \u306F RFC 4180 \u6E96\u62E0\u3002`ENCODING` \u3067 UTF-8 / Shift_JIS\u3001BOM \u8A31\u5BB9\u3002\r\n\r\n### JSON \u306E\u53D6\u8FBC\r\n\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D) FROM JSON payload;\r\n```\r\n\r\n- **\u53B3\u5BC6 10 \u9032\u30C7\u30B3\u30FC\u30C9**\uFF08\u5B57\u53E5\u3092\u4FDD\u6301\u3057\u3001\u5B89\u5168\u6574\u6570\u306E\u307F\u6570\u5024\u5316\u3002\u7CBE\u5EA6\u304C\u5FC5\u8981\u306A NUMBER \u306F JSON \u5074\u3067\u6587\u5B57\u5217\u3068\u3057\u3066\u6E21\u3059\uFF09\u3002\r\n- **\u5168\u968E\u5C64\u3067\u91CD\u8907\u30AD\u30FC\u3092\u62D2\u5426**\u3002`null` / \u6B20\u843D / \u5B58\u5728\u306E\u533A\u5225\u3042\u308A\u3002\r\n- JSON \u306F UTF-8 \u56FA\u5B9A\uFF08`ENCODING` \u4E0D\u53EF\uFF09\u3002\u5C04\u5F71\u30FB`BY NAME`\u30FB`NO HEADER` \u306F CSV \u5C02\u7528\u3002\r\n\r\n### cli-kintone \u4E92\u63DB\uFF08`BY NAME` \u30FB\u30EC\u30B3\u30FC\u30C9\u756A\u53F7 UPDATE\uFF09\r\n\r\n`cli-kintone record export` \u306E CSV \u3092\u305D\u306E\u307E\u307E\u623B\u305B\u307E\u3059\u3002\r\n\r\n- `BY NAME`: \u30D8\u30C3\u30C0\u3092\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u3068\u3057\u3066\u5BFE\u5FDC\u3002**\u66F8\u8FBC\u307F\u4E0D\u53EF\u306E\u65E2\u77E5\u5217**\uFF08`$id`\u30FB\u4F5C\u6210\u8005\u30FB\u66F4\u65B0\u65E5\u6642\u306A\u3069\uFF09\u306F\u76E3\u67FB\u30ED\u30B0\u3092\u6B8B\u3057\u3066\u7121\u8996\u3001**\u672A\u77E5\u5217**\u306F\u65E2\u5B9A\u3067\u62D2\u5426\uFF08`IGNORE UNKNOWN COLUMNS` \u3067\u7121\u8996\uFF09\u3002\u8907\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9\u306F\u30BB\u30EB\u5185\u6539\u884C\uFF08LF\uFF09\u3067\u5206\u5272\u3002\r\n- `IMPORT UPDATE \u2026 MATCH RECORD NUMBER SOURCE <\u30D8\u30C3\u30C0>`: \u30EC\u30B3\u30FC\u30C9\u756A\u53F7\u3067\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u3092**\u7D14 UPDATE**\uFF08INSERT 0\u30FB\u756A\u53F7\u306F\u7167\u5408\u5C02\u7528\u3067\u66F8\u304D\u63DB\u3048\u306A\u3044\uFF09\u3002`ON DUPLICATE` \u3068\u306F\u4F75\u7528\u4E0D\u53EF\u3002\r\n\r\n```sql\r\nIMPORT UPDATE INTO APP100 (\u91D1\u984D)\r\nFROM CSV exported BY NAME\r\nMATCH RECORD NUMBER SOURCE `\u30EC\u30B3\u30FC\u30C9\u756A\u53F7`;\r\n```\r\n\r\n### \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306E\u53D6\u8FBC\r\n\r\n\u610F\u5473\u8AD6\u306F\u30BD\u30FC\u30B9\u7A2E\u5225\u3067\u7570\u306A\u308A\u307E\u3059\u3002\r\n\r\n- **JSON\uFF08\u30CD\u30B9\u30C8\u914D\u5217\uFF09**: \u65B0\u898F INSERT / `ON DUPLICATE` UPSERT\u3002\u884C ID \u3092\u6301\u305F\u305A\u3001\u89AA\u5185\u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306F**\u5168\u7F6E\u63DB**\uFF08\u518D\u63A1\u756A\uFF09\u3002`ROW ID SOURCE` \u306F\u4E0D\u53EF\u3002\r\n- **CSV `*` \u5F62\u5F0F**\uFF08cli-kintone export\uFF09: **`IMPORT UPDATE` \u5C02\u7528**\u3002`BY NAME` \uFF0B `MATCH RECORD NUMBER SOURCE` \uFF0B `REPLACE SUBTABLES (...)` \uFF0B \u5404\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306E `ROW ID SOURCE <\u30D8\u30C3\u30C0>` \u304C\u5FC5\u9808\u3002\u884C ID \u3092\u4FDD\u6301\u3057\u3066\u66F4\u65B0\u3057\u3001\u30BD\u30FC\u30B9\u306B\u7121\u3044\u884C\u306F\u524A\u9664\u3002\r\n\r\n```sql\r\n-- JSON: \u660E\u7D30\u3092\u6301\u3064\u30EC\u30B3\u30FC\u30C9\u3092\u65B0\u898F\u767B\u9332\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u660E\u7D30(\u54C1\u540D, \u6570\u91CF)) FROM JSON payload;\r\n\r\n-- CSV *: \u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u306E\u660E\u7D30\u3092\u5168\u7F6E\u63DB\u66F4\u65B0\r\nIMPORT UPDATE INTO APP100 (\u660E\u7D30(\u54C1\u540D, \u6570\u91CF) ROW ID SOURCE `\u660E\u7D30_\u884CID`)\r\nFROM CSV exported BY NAME\r\nMATCH RECORD NUMBER SOURCE `\u30EC\u30B3\u30FC\u30C9\u756A\u53F7`\r\nREPLACE SUBTABLES (\u660E\u7D30);\r\n```\r\n\r\n- **\u7834\u58CA\u7684\u5168\u7F6E\u63DB\uFF08JSON \u306E\u30CD\u30B9\u30C8\u914D\u5217\uFF0FCSV \u306E `REPLACE SUBTABLES`\uFF09\u306F\u3001\u524A\u9664\u5185\u8A33\u3092\u78BA\u8A8D\u8868\u793A\u3067\u304D\u308B\u9762\u3067\u306E\u307F\u5B9F\u884C**\uFF08fail-closed\uFF09\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0\u306B\u5897\u6E1B\u30B5\u30DE\u30EA\u3092\u8868\u793A\u3057\u307E\u3059\u3002JSON UPSERT \u3082\u65E2\u5B58\u306E\u5B50\u884C\u3092\u524A\u9664\u3057\u3066\u5168\u7F6E\u63DB\u3057\u307E\u3059\uFF08`REPLACE SUBTABLES` \u306F\u66F8\u304B\u306A\u3044\u30FB\u66F8\u304F\u3068\u69CB\u6587\u30A8\u30E9\u30FC\uFF09\u3002\r\n- **MCP \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB mutation \u3092\u5E38\u306B fail-closed**\uFF08\u524A\u9664\u5185\u8A33\u3092\u5BFE\u8A71\u627F\u8A8D\u3067\u304D\u306A\u3044\u305F\u3081\uFF09\u3002\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u66F8\u8FBC\u307F\u306F CLI / \u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u884C\u3044\u3001MCP \u306F `ksql_query` \u306E `VALIDATE ONLY`\uFF0F`ksql_explain` \u306E `EXPLAIN` \u307E\u3067\u3002\r\n\r\n### \u691C\u8A3C\u30FB\u30C1\u30A7\u30C3\u30AF\u30FB\u9694\u96E2\r\n\r\n`VALIDATE ONLY`\uFF08\xA717.1\uFF09\u30FB`ON ERROR SKIP INTO #err`\uFF08\xA717.2\uFF09\u30FB`CHECK`\uFF08\xA717.3\uFF09\u3092 DML \u3068\u540C\u3058\u610F\u5473\u8AD6\u3067\u5229\u7528\u3067\u304D\u307E\u3059\u3002\u306A\u304A \xA717.1 \u306F\u4E00\u822C DML \u3067\u306F\u300C\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB DML \u975E\u5BFE\u5FDC\u300D\u3067\u3059\u304C\u3001**IMPORT \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306F\u305D\u306E\u4F8B\u5916**\u3067 `VALIDATE ONLY` \u3092\u5B9F\u884C\u3067\u304D\u307E\u3059\uFF08read-only \u306E\u305F\u3081\u5168\u9762\u3067\u53EF\uFF09\u3002\r\n\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D) FROM CSV sales BY NAME\r\nCHECK WHEN \u91D1\u984D < 0 THEN '\u91D1\u984D\u304C\u8CA0\u3067\u3059'\r\nON ERROR SKIP INTO #err REJECT LIMIT 100;\r\nSELECT * FROM #err;\r\n```\r\n\r\n**MCP \u306E\u632F\u308A\u5206\u3051**: \u30D5\u30E9\u30C3\u30C8\uFF08\u89AA\u306E\u307F\uFF09\u306E\u66F8\u8FBC\u307F IMPORT \u306F `ksql_mutate`\u3001`VALIDATE ONLY`\uFF08read-only\uFF09\u306F `ksql_query`\u3001`EXPLAIN` \u306F `ksql_explain`\u3001\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB mutation \u306F Unsupported\u3002\r\n\r\n### \u5236\u9650\r\n\r\n- **\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\uFF08FILE\uFF09\u306F\u975E\u5BFE\u5FDC**\uFF08cli-kintone \u3092\u4F7F\u3046\uFF09\u3002\r\n- **\u53D6\u8FBC\u884C\u6570\u306E\u4E0A\u9650 `maxRecords` \u306F\u9762\u30FB\u7D4C\u8DEF\u3067\u7570\u306A\u308B**\uFF08\u8D85\u904E\u306F\u30B5\u30A4\u30EC\u30F3\u30C8\u5207\u308A\u6368\u3066\u305B\u305A fail-closed\uFF09:\r\n - CLI = \u65E2\u5B9A **500**\uFF08`--max-records` \u3067\u62E1\u5F35\uFF09\u3002\r\n - \u30D7\u30E9\u30B0\u30A4\u30F3 = \u521D\u671F\u5024 **3000**\uFF08UI \u3067\u5909\u66F4\u53EF\uFF09\u3002\r\n - MCP = \u901A\u5E38\u306E\u66F8\u8FBC\u307F mutation \u306F `dmlMaxRows`\uFF08\uFF0B1\uFF09\u3067\u89E3\u6C7A\u3001`ON ERROR SKIP` / `VALIDATE ONLY` \u306F\u901A\u5E38\u306E runtime `maxRecords` \u89E3\u6C7A\u306B\u623B\u308B\u3002\r\n - **CSV \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u7F6E\u63DB**\u3067\u306F\u3001\u540C\u3058 `maxRecords` \u304C\u53D6\u8FBC\u89AA\u4EF6\u6570\u3060\u3051\u3067\u306A\u304F**\u884C ID \u6240\u6709\u6A29\u691C\u67FB\u306E\u305F\u3081\u306E\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u5168\u4EF6\u8D70\u67FB**\u306B\u3082\u9069\u7528\u3055\u308C\u308B\u3002\u65E2\u5B9A\u3092\u8D85\u3048\u308B\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u304C\u3042\u308B\u3068\u3001\u53D6\u8FBC\u4EF6\u6570\u304C\u5C11\u306A\u304F\u3066\u3082 fail-closed \u306B\u306A\u308B\u3002\r\n- **CSV \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306F UPDATE \u5C02\u7528**\u3002\u65B0\u898F\u767B\u9332\u306F JSON\u3002\r\n- \u6A19\u6E96\u30B9\u30DA\u30FC\u30B9\u30FB\u30B2\u30B9\u30C8\u30B9\u30DA\u30FC\u30B9\u306E\u4E21\u65B9\u3067\u52D5\u4F5C\u3002\r\n\r\n---", uri: "ksql://language-reference/18-delete" }, "19-subtable-virtual-table": { heading: "19. \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB", text: "## 19. \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\r\n\r\n\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306F `APP100$\u660E\u7D30` \u5F62\u5F0F\u306E\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u3068\u3057\u3066\u64CD\u4F5C\u3067\u304D\u307E\u3059\u3002\r\n\r\n### \u30B7\u30B9\u30C6\u30E0\u5217\r\n\r\n| \u5217\u540D | \u610F\u5473 | \u6BD4\u8F03\u578B |\r\n|------|------|------|\r\n| `_pid` | \u89AA\u30EC\u30B3\u30FC\u30C9 ID\uFF08`$id`\uFF09 | \u6570\u5024 |\r\n| `_rid` | \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u884C ID | \u6587\u5B57\u5217 |\r\n| `_idx` | \u89AA\u30EC\u30B3\u30FC\u30C9\u5185\u306E\u884C\u9806\uFF080-based\uFF09 | \u6570\u5024 |\r\n\r\n- \u30B7\u30B9\u30C6\u30E0\u5217\u306F SELECT \u306E `WHERE` / `ORDER BY` \u3067\u53C2\u7167\u3067\u304D\u3001\u5168\u6BD4\u8F03\u6F14\u7B97\u5B50\u30FB`BETWEEN` / `IN` / `IS NULL` / `LIKE` \u306B\u5BFE\u5FDC\u3057\u307E\u3059\uFF08\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB SELECT \u306F\u5E38\u306B\u30ED\u30FC\u30AB\u30EB\u5168\u4EF6\u8A55\u4FA1\u306E\u305F\u3081 kintone \u3078\u306F\u62BC\u3057\u4E0B\u3052\u307E\u305B\u3093\uFF09\u3002\r\n- \u6BD4\u8F03\u578B\u306F\u4E0A\u8868\u306E\u3068\u304A\u308A\u3067\u3001`_pid` / `_idx` \u306F\u6570\u5024\u3001`_rid` \u306F\u4E0D\u900F\u660E\u306A\u6587\u5B57\u5217\u3068\u3057\u3066\u6BD4\u8F03\u3057\u307E\u3059\uFF08\u4F8B: `_idx > 2` \u306F\u6570\u5024\u9806\u3001`_rid` \u306F\u8F9E\u66F8\u9806\uFF09\u3002\r\n- \u672A\u4FDD\u5B58\u884C\u3067\u306F `_rid` \u304C\u7A7A\u306E\u305F\u3081 `_rid IS NULL` \u304C\u771F\u306B\u306A\u308A\u307E\u3059\u3002\r\n- \u89AA\u9805\u76EE\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8\u7D4C\u7531\u306E `_p._pid` \u7B49\uFF08\u30B7\u30B9\u30C6\u30E0\u5217\u3092 `_p.` \u4FEE\u98FE\u3057\u305F\u5F62\uFF09\u306F\u7121\u52B9\u3067\u3059\u3002\r\n\r\n### \u89AA\u9805\u76EE\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8\r\n\r\n- `_p.\u9805\u76EE\u540D` \u3067\u89AA\u9805\u76EE\u3092\u53C2\u7167\u53EF\u80FD\r\n- `_p.*` \u3067\u89AA\u9805\u76EE\u3092\u4E00\u62EC\u5C55\u958B\r\n- `SELECT *` \u306B\u306F `_p.*` \u3092\u6697\u9ED9\u8FFD\u52A0\u3057\u306A\u3044\r\n\r\n```sql\r\nSELECT _p.\u4F1D\u7968\u756A\u53F7, \u5546\u54C1\u30B3\u30FC\u30C9, \u6570\u91CF\r\nFROM APP100$\u660E\u7D30\r\nWHERE _pid = 123\r\n```\r\n\r\n### \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB DML\r\n\r\n```sql\r\nINSERT INTO APP100$\u660E\u7D30 (_pid, \u5546\u54C1\u30B3\u30FC\u30C9, \u6570\u91CF) VALUES (123, 'A-001', 2)\r\n\r\nUPDATE APP100$\u660E\u7D30\r\nSET \u6570\u91CF = 5\r\nWHERE _pid = 123 AND _rid = '67890'\r\n\r\nDELETE FROM APP100$\u660E\u7D30\r\nWHERE _pid = 123 AND _rid = '67890'\r\n```\r\n\r\n- `UPDATE` / `DELETE` \u306F\u5B89\u5168\u306E\u305F\u3081 `_rid` \u6761\u4EF6\u3092\u5FC5\u9808\u3068\u3059\u308B\r\n\r\n---\r\n\r\n## 19.1 APPLY \u30D6\u30ED\u30C3\u30AF\uFF08\u30C6\u30FC\u30D6\u30EB\u5916\u30FB\u5185\u306E\u540C\u6642\u66F4\u65B0\uFF09\r\n\r\n`UPDATE` / `INSERT` / `UPSERT` \u306B `APPLY` \u30D6\u30ED\u30C3\u30AF\u3092\u4ED8\u3051\u308B\u3068\u3001**\u89AA\uFF08\u30C6\u30FC\u30D6\u30EB\u5916\uFF09\u9805\u76EE\u3068\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\uFF08\u30C6\u30FC\u30D6\u30EB\u5185\uFF09\u884C\u30921\u6587\uFF1D1 PUT \u30EC\u30B3\u30FC\u30C9\u3067\u540C\u6642\u306B\u66F4\u65B0**\u3067\u304D\u307E\u3059\u3002kintone \u306F\u66F8\u304D\u8FBC\u307F\u6642\u306B\u30EC\u30B3\u30FC\u30C9\u5168\u4F53\u3092\u518D\u691C\u8A3C\u3059\u308B\u305F\u3081\u3001\u30C6\u30FC\u30D6\u30EB\u5185\u306B\u65E2\u5B58\u9055\u53CD\u304C\u3042\u308B\u3068\u30C6\u30FC\u30D6\u30EB\u5916\u9805\u76EE\u3060\u3051\u306E `UPDATE` \u3082\u5931\u6557\u3057\u307E\u3059\u304C\u3001`APPLY` \u3067\u9055\u53CD\u30BB\u30EB\u3078\u59A5\u5F53\u306A\u5024\u3092\u540C\u6642\u306B\u30BB\u30C3\u30C8\u3057\u3066\u30EC\u30B3\u30FC\u30C9\u5168\u4F53\u3092 valid \u5316\u3059\u308B\u300C\u4FEE\u5FA9\u66F8\u304D\u8FBC\u307F\u300D\u304C\u53EF\u80FD\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u78BA\u5B9A'\r\nWHERE $id = 5\r\nAPPLY \u660E\u7D30 (\r\n PATCH SET \u6570\u91CF = 0 WHERE \u6570\u91CF < 0; -- \u65E2\u5B58\u884C\u306E\u30BB\u30EB\u66F4\u65B0\r\n APPEND (\u5546\u54C1\u30B3\u30FC\u30C9, \u6570\u91CF) VALUES ('A-001', 1); -- \u884C\u8FFD\u52A0\r\n REMOVE WHERE \u5EC3\u756A = 'true' -- \u884C\u524A\u9664\r\n)\r\n```\r\n\r\n### \u64CD\u4F5C\r\n\r\n| \u64CD\u4F5C | \u610F\u5473 |\r\n|------|------|\r\n| `PATCH SET \u2026 {WHERE \u884C\u6761\u4EF6 \\| ALL ROWS \\| _idx = n \\| _rid = 'id'}` | \u65E2\u5B58\u884C\u306E\u30BB\u30EB\u66F4\u65B0\uFF08\u884C id\u30FB\u884C\u9806\u30FB\u672A\u6307\u5B9A\u30BB\u30EB\u3092\u4FDD\u6301\uFF09 |\r\n| `APPEND (\u5B50\u2026) VALUES (\u2026)` | \u884C\u8FFD\u52A0\uFF08\u672A\u6307\u5B9A\u306E\u5B50\u306F\u65E2\u5B9A\u5024\u3067\u660E\u793A\u88DC\u5B8C\uFF09 |\r\n| `REMOVE {WHERE \u884C\u6761\u4EF6 \\| _idx = n \\| _rid = 'id'}` | \u884C\u524A\u9664\uFF08\u5B58\u7D9A\u884C\u306F\u5168\u5217\u3092\u4FDD\u6301\uFF09 |\r\n\r\n- **\u591A\u5024\u30D5\u30A3\u30FC\u30EB\u30C9**\uFF08`CHECK_BOX` / `MULTI_SELECT` / `USER_SELECT` \u7B49\uFF09: `APPLY <\u591A\u5024> (ADD '\u5024'; REMOVE '\u5024')`\u3002\r\n- 1\u6587\u306B\u8907\u6570\u30C6\u30FC\u30D6\u30EB\uFF0F\u591A\u5024\u306E `APPLY` \u30D6\u30ED\u30C3\u30AF\u3092\u4F75\u8A18\u3067\u304D\u307E\u3059\u3002\r\n\r\n### \u884C\u30A2\u30C9\u30EC\u30C3\u30B7\u30F3\u30B0\u30FB\u884C\u6570\u8868\u660E\r\n\r\n- \u884C\u30BB\u30EC\u30AF\u30BF: `ALL ROWS`\uFF08**\u660E\u793A\u5FC5\u9808**\uFF09\u30FB`WHERE \u884C\u6761\u4EF6`\u30FB`_idx`\uFF080-based\uFF09\u30FB`_rid`\uFF08\u884C ID\uFF09\u3002\r\n- `EXPECT ROWS n | BETWEEN a AND b | AT LEAST n | AT MOST n` \u3067\u5BFE\u8C61\u884C\u6570\u3092\u8868\u660E\u3067\u304D\u3001\u4E0D\u4E00\u81F4\u306F\u66F8\u304D\u8FBC\u307F\u524D\u306B `ArgumentError`\u3002\r\n\r\n### \u610F\u5473\u8AD6\u30FB\u5B89\u5168\u30EB\u30FC\u30EB\r\n\r\n- **\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\u610F\u5473\u8AD6**: \u30BB\u30EC\u30AF\u30BF\u3068\u53F3\u8FBA\u306F\u66F4\u65B0\u524D\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\u3067\u8A55\u4FA1\u3057\u3001\u540C\u4E00\u6587\u5185\u306E `APPEND` \u884C\u306F\u540C\u6587\u306E `PATCH`/`REMOVE` \u304B\u3089\u898B\u3048\u307E\u305B\u3093\u3002\r\n- **post-image \u691C\u8A3C**: \u5909\u7570\u5F8C\u306E\u30EC\u30B3\u30FC\u30C9\u5168\u4F53\u3092\u66F8\u304D\u8FBC\u307F\u524D\u306B\u691C\u8A3C\u3057\u3001\u9055\u53CD\u306F\u884C\u30ED\u30B1\u30FC\u30BF\u4ED8\u304D\u3067\u5831\u544A\u3057\u307E\u3059\u3002\r\n- **\u8907\u6570\u89AA**: \u89AA `WHERE` \u304C\u8907\u6570\u30EC\u30B3\u30FC\u30C9\u306B\u4E00\u81F4\u3059\u308B `UPDATE APPLY` \u306B\u5BFE\u5FDC\uFF081\u5BFE\u8C61\u89AA=1 PUT\u30FB100\u4EF6/\u30C1\u30E3\u30F3\u30AF\u30FB**\u975E\u30C8\u30E9\u30F3\u30B6\u30AF\u30B7\u30E7\u30F3**\u30FB\u81EA\u52D5\u30EA\u30C8\u30E9\u30A4\u306A\u3057\u30FB\u90E8\u5206\u6210\u529F\u3042\u308A\uFF09\u3002`INSERT APPLY`\uFF08\u89AA\u4F5C\u6210\uFF0B\u521D\u671F\u884C\uFF09\u30FB`UPSERT APPLY`\uFF08`ON INSERT` / `ON UPDATE` \u5206\u5C90\uFF09\u3082\u53EF\u3002\r\n- **\u30AC\u30FC\u30C9**: revision \u30AC\u30FC\u30C9\u5FC5\u9808\u3002`dmlMaxRows`\uFF08\u89AA\u4EF6\u6570\uFF09\u3068 `dmlMaxSubtableRows`\uFF08\u5909\u66F4\u5B50\u884C\u6570\u30FB\u65E2\u5B9A500\uFF09\u306E\u4E8C\u91CD\u30AC\u30FC\u30C9\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u300C\u6700\u5927\u53D6\u5F97\u4EF6\u6570\u300D\u8A2D\u5B9A\u3092\u4E21\u30AC\u30FC\u30C9\u3078\u517C\u7528\u3057\u307E\u3059\u3002\r\n- **MCP**: \u3059\u3079\u3066\u306E `APPLY` mutation \u306F\u5B9F\u884C\u524D\u306B fail-closed\uFF08`allowDml` / `dmlMaxSubtableRows` \u3067\u3082\u89E3\u7981\u3055\u308C\u307E\u305B\u3093\uFF09\u3002`VALIDATE ONLY` / `EXPLAIN` \u306F\u8A31\u53EF\u3002\r\n\r\n---", uri: "ksql://language-reference/19-subtable-virtual-table" }, "20-reorder": { heading: "20. REORDER", text: "## 20. REORDER\r\n\r\n\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u884C\u3092\u89AA\u5358\u4F4D\u3067\u4E26\u3073\u66FF\u3048\u307E\u3059\u3002\r\n\r\n```sql\r\nREORDER APP100$\u660E\u7D30\r\nBY \u5546\u54C1\u30B3\u30FC\u30C9 ASC, \u7D0D\u671F DESC\r\nWHERE _pid = 123\r\n```\r\n\r\n\u5168\u4EF6\u5BFE\u8C61\u306E\u660E\u793A\u69CB\u6587:\r\n\r\n```sql\r\nREORDER ALL APP100$\u660E\u7D30\r\nBY \u5546\u54C1\u30B3\u30FC\u30C9 ASC\r\n```\r\n\r\n\u30EB\u30FC\u30EB:\r\n- `REORDER` \u306F `WHERE` \u5FC5\u9808\r\n- `REORDER ALL` \u306F `WHERE` \u4F75\u7528\u4E0D\u53EF\r\n- `_idx` \u306F\u53C2\u7167\u5C02\u7528\uFF08`UPDATE SET _idx = ...` \u4E0D\u53EF\uFF09\r\n- \u4E26\u3073\u66FF\u3048\u66F4\u65B0\u6642\u306F\u884C `id` \u306E\u307F\u9001\u4FE1\u3057\u3001\u884C\u5024\u306F\u518D\u9001\u3057\u306A\u3044\uFF08\u30EB\u30C3\u30AF\u30A2\u30C3\u30D7\u518D\u8A55\u4FA1\u5F71\u97FF\u3092\u6291\u5236\uFF09\r\n\r\n---", uri: "ksql://language-reference/20-reorder" }, "21-subqueries": { heading: "21. \u30B5\u30D6\u30AF\u30A8\u30EA", text: "## 21. \u30B5\u30D6\u30AF\u30A8\u30EA\r\n\r\n### \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\uFF08SELECT \u5217\u30FBHAVING\uFF09\r\n\r\nSELECT \u5217\u3084 HAVING \u53E5\u3067\u3082 1 \u884C 1 \u5217\u3092\u8FD4\u3059\u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\n-- SELECT \u5217: \u5168\u4EF6\u6570\u30FB\u5408\u8A08\u3092\u3059\u3079\u3066\u306E\u884C\u306B\u4ED8\u52A0\r\nSELECT\r\n \u9867\u5BA2\u540D,\r\n \u91D1\u984D,\r\n (SELECT COUNT(*) FROM APP100) AS \u7DCF\u4EF6\u6570,\r\n (SELECT SUM(\u91D1\u984D) FROM APP100) AS \u5408\u8A08\u91D1\u984D\r\nFROM APP100\r\nWHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5B8C\u4E86'\r\n\r\n-- HAVING \u3067\u30B5\u30D6\u30AF\u30A8\u30EA\r\nSELECT \u62C5\u5F53\u8005, SUM(\u91D1\u984D) AS \u5408\u8A08\r\nFROM APP100\r\nGROUP BY \u62C5\u5F53\u8005\r\nHAVING SUM(\u91D1\u984D) > (SELECT AVG(\u91D1\u984D) FROM APP100) * 2\r\n```\r\n\r\n\u5217\u306E\u30A8\u30A4\u30EA\u30A2\u30B9\u3092\u7701\u7565\u3057\u305F\u5834\u5408\u306F `(subquery)` \u304C\u5217\u540D\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n### \u30B5\u30D6\u30AF\u30A8\u30EA\u4E00\u89A7\r\n\r\n| \u69CB\u6587 | \u8A18\u8FF0\u7B87\u6240 | \u5099\u8003 |\r\n|---|---|---|\r\n| `IN (SELECT ...)` | WHERE | 1 \u5217\u76EE\u306E\u5024\u30BB\u30C3\u30C8\u3092 IN \u30EA\u30B9\u30C8\u3068\u3057\u3066\u4F7F\u7528 |\r\n| `NOT IN (SELECT ...)` | WHERE | \u9664\u5916\u6761\u4EF6 |\r\n| `EXISTS (SELECT ...)` | WHERE | 1 \u4EF6\u4EE5\u4E0A\u8FD4\u305B\u3070\u771F |\r\n| `NOT EXISTS (SELECT ...)` | WHERE | 0 \u4EF6\u306A\u3089\u771F |\r\n| `(SELECT ...)` | WHERE \u53F3\u8FBA\u30FBSELECT \u5217\u30FBHAVING \u53F3\u8FBA | \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\uFF081 \u884C 1 \u5217\u3002GROUP BY \u306A\u3057\u306E\u96C6\u8A08\u306F 0 \u4EF6\u3067\u3082 1 \u884C = `0` \u3092\u8FD4\u3059 \u2014 \xA78\uFF09 |\r\n\r\n**\u5171\u901A\u5236\u7D04:**\r\n- **\u975E\u76F8\u95A2\u306E\u307F\u5BFE\u5FDC** \u2014 \u5916\u5074\u30C6\u30FC\u30D6\u30EB\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\r\n- \u3059\u3079\u3066 FULL_SCAN \u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u81EA\u4F53\u3082 SIMPLE / FULL_SCAN \u3092\u81EA\u52D5\u5224\u5B9A\u3057\u307E\u3059\r\n- \u30B5\u30D6\u30AF\u30A8\u30EA\u306F 1 \u56DE\u3060\u3051\u5B9F\u884C\u3055\u308C\u3001\u5168\u884C\u306B\u540C\u3058\u7D50\u679C\u304C\u9069\u7528\u3055\u308C\u307E\u3059\r\n\r\n---", uri: "ksql://language-reference/21-subqueries" }, "22-limitations": { heading: "22. \u5236\u9650\u4E8B\u9805", text: "## 22. \u5236\u9650\u4E8B\u9805\r\n\r\n### \u6B63\u898F\u8868\u73FE\u306E\u9069\u7528\u9650\u754C\r\n\r\n`REGEXP_LIKE` / `REGEXP_REPLACE` / `REGEXP_SUBSTR` \u306B\u5B89\u5168\u6027\u30B2\u30FC\u30C8\u3084\u5B9F\u884C\u6642\u9593\u5236\u9650\u306F\u3042\u308A\u307E\u305B\u3093\u3002ReDoS \u3067\u540C\u671F\u51E6\u7406\u304C\u66B4\u8D70\u3059\u308B\u3068 kSQL \u81EA\u8EAB\u304B\u3089\u306F\u4E2D\u65AD\u3067\u304D\u307E\u305B\u3093\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u30BF\u30D6\u5F37\u5236\u7D42\u4E86\u3001CLI \u306F Ctrl+C\u3001MCP \u306F\u30D7\u30ED\u30BB\u30B9\u518D\u8D77\u52D5\u3067\u5FA9\u65E7\u3057\u307E\u3059\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306F\u540C\u3058\u30BF\u30D6\u306E\u672A\u4FDD\u5B58\u7DE8\u96C6\u3068 SQL\u3001MCP \u3067\u306F\u540C\u4E00\u30D7\u30ED\u30BB\u30B9\u306E\u5168\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u5DFB\u304D\u8FBC\u307F\u307E\u3059\u3002\r\n\r\nECMAScript \u6B63\u898F\u8868\u73FE\u306F\u30DB\u30B9\u30C8\u306E\u30D6\u30E9\u30A6\u30B6\uFF0FNode \u3068\u305D\u306E\u7248\u306B\u4F9D\u5B58\u3057\u307E\u3059\u3002`\\p{}`\u3001Unicode \u30E2\u30FC\u30C9\u3068 `i` \u306E case folding\u3001\u65B0\u69CB\u6587\u306E\u53D7\u7406\u53EF\u5426\u306A\u3069\u306F\u540C\u3058 SQL \u3067\u3082\u9762\u3054\u3068\u306B\u7570\u306A\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\u7D50\u679C\u3092 `UPDATE SET` \u307E\u305F\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u7D4C\u7531\u306E `UPDATE ... FROM` \u3067\u4FDD\u5B58\u3059\u308B\u3068\u3001\u305D\u306E\u5DEE\u304C\u4FDD\u5B58\u30C7\u30FC\u30BF\u3078\u6B8B\u308B\u305F\u3081\u3001\u66F8\u304D\u623B\u3057\u74B0\u5883\u3092\u56FA\u5B9A\u3057\u3066\u4E8B\u524D\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n### \u30B5\u30DD\u30FC\u30C8\u3057\u3066\u3044\u306A\u3044\u69CB\u6587\r\n\r\n| \u6A5F\u80FD | \u72B6\u6CC1 |\r\n|------|------|\r\n| \u76F8\u95A2\u30B5\u30D6\u30AF\u30A8\u30EA | \u975E\u5BFE\u5FDC\uFF08\u975E\u76F8\u95A2 IN/EXISTS \u306F\u5BFE\u5FDC\uFF09 |\r\n| INTERSECT / EXCEPT | \u975E\u5BFE\u5FDC |\r\n| \u518D\u5E30 CTE | \u975E\u5BFE\u5FDC |\r\n| FULL OUTER JOIN | \u975E\u5BFE\u5FDC |\r\n| UPDATE \u306E\u6C4E\u7528 JOIN | \u975E\u5BFE\u5FDC\uFF08`UPDATE ... FROM` \u306E `$id`\uFF0F\u6587\u5B57\u5217\uFF081\u884C\uFF09\uFF0F\u6570\u5024\u30AD\u30FC\u306B\u3088\u308B\u5358\u4E00\u7B49\u5024\u306E\u307F\u5BFE\u5FDC\uFF09 |\r\n| \u30C8\u30E9\u30F3\u30B6\u30AF\u30B7\u30E7\u30F3 | kintone API \u306E\u5236\u7D04\u306B\u3088\u308A\u975E\u5BFE\u5FDC\uFF08\u30D0\u30C3\u30C1\u5B9F\u884C\u3082\u975E\u30A2\u30C8\u30DF\u30C3\u30AF\uFF09 |\r\n| DML \u3092\u542B\u3080\u30D0\u30C3\u30C1\uFF08\u8907\u6587\uFF09 | \u5BFE\u5FDC\uFF08`ksql_mutate` / CLI `--allow-dml` / \u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u6587\u3054\u3068\u306E\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0\u3002\u5E38\u306B fail-fast\u3002\u2192 [\xA725](#25-\u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB)\uFF09 |\r\n| \u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3078\u306E DML | \u975E\u5BFE\u5FDC\uFF08`CREATE TEMP TABLE ... AS SELECT` / `DROP TEMP TABLE` \u306E\u307F\uFF09 |\r\n| `ASSERT` \u306E\u8907\u5408\u6761\u4EF6\uFF08`AND` / `OR`\uFF09 | \u975E\u5BFE\u5FDC\uFF08\u8907\u6570\u306E `ASSERT` \u6587\u306B\u5206\u3051\u3066\u66F8\u304F\u3002\u2192 [\xA726](#26-assert)\uFF09 |\r\n| \u30D0\u30C3\u30C1\u5909\u6570\u306E\u9AD8\u5EA6\u306A\u5229\u7528 | `SET @x = (SELECT ...)`\u3001`DECLARE @x = default`\u3001SELECT \u5B9A\u6570\u5217 `@x AS alias`\u3001\u6587\u5B57\u5217\u914D\u5217 `SET @list=['A','B']` \u3068 `IN @list`\u3001CLI/MCP \u5916\u90E8\u6CE8\u5165\u306B\u5BFE\u5FDC\u3002`NULL` \u4EE3\u5165\u30FB\u30B5\u30D6\u30AF\u30A8\u30EA\u7D50\u679C\u3078\u306E\u7B97\u8853\u306F\u73FE\u6642\u70B9\u3067\u975E\u5BFE\u5FDC\uFF08\u2192 [\xA725 \u30D0\u30C3\u30C1\u5909\u6570](#25-\u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB)\uFF09 |\r\n| \u66F8\u304D\u8FBC\u307F\u7CFB API\uFF08POST / PUT / DELETE\uFF09\u306E\u81EA\u52D5\u30EA\u30C8\u30E9\u30A4 | \u975E\u5BFE\u5FDC\uFF08\u5FDC\u7B54\u55AA\u5931\u6642\u306E\u4E8C\u91CD\u5B9F\u884C\u3092\u907F\u3051\u308B\u305F\u3081\u3002\u30EA\u30C8\u30E9\u30A4\u306F GET \u7CFB\u9650\u5B9A \u2014 \u5BFE\u8C61: 408/429/502/503/504\u3002\u5FC5\u8981\u306A\u3089\u547C\u3073\u51FA\u3057\u5074\u3067\u51AA\u7B49\u306A\u518D\u5B9F\u884C\uFF08UPSERT \u7B49\uFF09\u3092\u8A2D\u8A08\u3059\u308B\uFF09 |\r\n| `DELETE` \u3067\u306E `APP@profile`\uFF08CLI \u62E1\u5F35\uFF09 | \u672A\u5BFE\u5FDC\uFF08`ArgumentError: @profile is not supported for DELETE yet.`\uFF09 |\r\n| **\u30D7\u30ED\u30BB\u30B9\u7BA1\u7406\u306E\u30B9\u30C6\u30FC\u30BF\u30B9\u30FB\u4F5C\u696D\u8005\u306E UPDATE** | **\u5BFE\u8C61\u5916**\uFF08`/k/v1/records/status.json` \u304C\u5FC5\u8981\u306A\u305F\u3081\uFF09 |\r\n\r\n### \u5B9F\u884C\u30E2\u30FC\u30C9\r\n\r\nkSQL \u306F\u4EE5\u4E0B\u306E\u6761\u4EF6\u306B\u5FDC\u3058\u3066\u81EA\u52D5\u7684\u306B\u5B9F\u884C\u30E2\u30FC\u30C9\u3092\u5207\u308A\u66FF\u3048\u307E\u3059\u3002\r\n\r\n| \u6761\u4EF6 | \u30E2\u30FC\u30C9 |\r\n|------|--------|\r\n| JOIN \u306A\u3057\u3001GROUP BY \u306A\u3057\u3001DISTINCT \u306A\u3057\u3001WHERE/ORDER BY \u306B\u95A2\u6570\u30FB\u7B97\u8853\u5F0F\u306A\u3057 | **SIMPLE\u5019\u88DC**\uFF08\u578B\xD7\u6F14\u7B97\u5B50\u80FD\u529B\u3068ORDER planner\u3067\u6700\u7D42\u6C7A\u5B9A\uFF09 |\r\n| JOIN \u3042\u308A / GROUP BY \u3042\u308A / DISTINCT / WHERE \u306B\u95A2\u6570\u30FB\u7B97\u8853\u5F0F\u30FBCASE WHEN / ORDER BY \u306B\u7B97\u8853\u5F0F | **FULL_SCAN**\uFF08\u5168\u4EF6\u53D6\u5F97\u3057\u3066 JS \u51E6\u7406\uFF09 |\r\n| WHERE \u306B IN (SELECT) / EXISTS / NOT EXISTS / \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA | **FULL_SCAN** |\r\n| SELECT \u5217\u306B\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA | **FULL_SCAN** |\r\n| SELECT \u5217\u306B\u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570 | **FULL_SCAN** |\r\n| UNION / UNION ALL | **FULL_SCAN** |\r\n| WITH \u53E5\uFF08\u5358\u7D14 CTE\uFF09\u2014 \u30A4\u30F3\u30E9\u30A4\u30F3\u5316\u3055\u308C\u308B | **SIMPLE**\uFF08kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\uFF09 |\r\n| WITH \u53E5\uFF08GROUP BY \u3042\u308A\u306E CTE\u30FB\u8907\u6570 CTE\u30FBCTE JOIN\uFF09 | **FULL_SCAN** |\r\n\r\nFULL_SCAN \u30E2\u30FC\u30C9\u306F\u5927\u91CF\u30EC\u30B3\u30FC\u30C9\u306E\u5834\u5408\u3001\u6642\u9593\u304C\u304B\u304B\u308A\u307E\u3059\u3002\r\n\r\n### \u53D6\u5F97\u4EF6\u6570\u306E\u4E0A\u9650\r\n\r\n- \u30A8\u30F3\u30B8\u30F3\u65E2\u5B9A\u5024: **10,000 \u4EF6**\r\n- CLI \u65E2\u5B9A\u5024: **500 \u4EF6**\uFF08`--max-records` \u3067\u5909\u66F4\u53EF\u80FD\uFF09\r\n- JOIN / GROUP BY / DISTINCT \u3092\u4F7F\u3046\u5834\u5408\u3001\u5168\u30C6\u30FC\u30D6\u30EB\u3092\u4E00\u62EC\u53D6\u5F97\u3059\u308B\u305F\u3081\u5927\u91CF\u30C7\u30FC\u30BF\u3067\u306F\u6642\u9593\u304C\u304B\u304B\u308A\u307E\u3059\r\n- \u30ED\u30FC\u30AB\u30EB`ORDER BY`\u3067\u4E0A\u9650\u306B\u9054\u3057\u305F\u5834\u5408\u3001`truncate`\u8A2D\u5B9A\u3067\u3082\u8AA4\u3063\u305Ftop-N\u3092\u8FD4\u3055\u305A\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\r\n\r\n### \u7B97\u8853\u306F\u6D6E\u52D5\u5C0F\u6570\u70B9\uFF08IEEE 754 \u500D\u7CBE\u5EA6\uFF09\r\n\r\n- \u7B97\u8853\u5F0F\u30FB\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u30FB\u96C6\u8A08\uFF08SUM/AVG\uFF09\u306F\u500D\u7CBE\u5EA6\u6D6E\u52D5\u5C0F\u6570\u70B9\u3067\u8A55\u4FA1\u3057\u307E\u3059\u3002\u5C0F\u6570\u306E\u8868\u73FE\u8AA4\u5DEE\uFF08`3000 * 1.1` = `3300.0000000000005`\uFF09\u30FB\u6709\u52B9\u6841 15\u301C17 \u6841\u30FB**\u7A7A\u30BB\u30EB= 0 \u6271\u3044**\u306E\u5236\u7D04\u304C\u3042\u308A\u307E\u3059\u3002\u8A73\u7D30\u3068\u56DE\u907F\u7B56\u306F \xA73\u300C\u7B97\u8853\u306E\u7CBE\u5EA6\u3068\u7A7A\u30BB\u30EB\u300D\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\r\n- \u53D6\u5F97\u3057\u305F\u6570\u5024\u305D\u306E\u3082\u306E\u306F\u6587\u5B57\u5217\u306E\u307E\u307E\u4FDD\u6301\u3059\u308B\u305F\u3081\u3001\u7B97\u8853\u3092\u901A\u3055\u306A\u3051\u308C\u3070\u6841\u843D\u3061\u3057\u307E\u305B\u3093\r\n\r\n### JOIN \u306E\u7B49\u5024\u7D50\u5408\u306E\u307F\u5BFE\u5FDC\r\n\r\n```sql\r\n-- OK: \u7B49\u5024\u7D50\u5408\r\nON a.\u9867\u5BA2ID = b.\u9867\u5BA2ID\r\n\r\n-- NG: \u7BC4\u56F2\u7D50\u5408\u30FB\u4E0D\u7B49\u5024\u7D50\u5408\u306F\u975E\u5BFE\u5FDC\r\nON a.\u91D1\u984D > b.\u4E0B\u9650\u91D1\u984D\r\n```\r\n\r\n### INSERT / UPDATE \u306E\u5024\r\n\r\n\u6587\u5B57\u5217\u30FB\u6570\u5024\uFF08`-5` / `+5` \u306E\u3088\u3046\u306A\u7B26\u53F7\u4ED8\u304D\u6570\u5024\u3092\u542B\u3080\uFF09\u30FB\u914D\u5217\u30EA\u30C6\u30E9\u30EB `[...]` \u304C\u6307\u5B9A\u53EF\u80FD\u3067\u3059\u3002INSERT / UPSERT VALUES \u306E\u7B26\u53F7\u76F4\u5F8C\u306F\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u3060\u3051\u3001UPDATE SET \u306E\u5358\u9805 `+` \u3082\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u76F4\u524D\u3060\u3051\u3067\u3059\u3002\r\n\u30E6\u30FC\u30B6\u30FC\u9078\u629E\u30FB\u7D44\u7E54\u9078\u629E\u30FB\u30B0\u30EB\u30FC\u30D7\u9078\u629E\u30FB\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9\u30FB\u8907\u6570\u9078\u629E\u30D5\u30A3\u30FC\u30EB\u30C9\u3078\u306E\u66F8\u304D\u8FBC\u307F\u3092\u30B5\u30DD\u30FC\u30C8\u3057\u307E\u3059\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u3092 `getFields()` \u3067\u81EA\u52D5\u53D6\u5F97\u3057\u3066\u5909\u63DB\uFF09\u3002\r\n\r\n\u4EE5\u4E0B\u306F\u5F15\u304D\u7D9A\u304D\u975E\u5BFE\u5FDC\u3067\u3059:\r\n\r\n| \u30D5\u30A3\u30FC\u30EB\u30C9\u578B | \u72B6\u6CC1 |\r\n|---|---|\r\n| \u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\uFF08FILE\uFF09 | \u30D0\u30A4\u30CA\u30EA\u9001\u4FE1\u304C\u5225 API \u306E\u305F\u3081\u975E\u5BFE\u5FDC |\r\n| CREATOR / MODIFIER | kintone API \u3067\u66F4\u65B0\u4E0D\u53EF |\r\n| SUBTABLE | \u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u7D4C\u7531\uFF08`APP100$\u660E\u7D30`\uFF09\u3067\u64CD\u4F5C |\r\n\r\n### LIKE \u306E\u6319\u52D5\r\n\r\nLIKE\u306F\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u306E\u6709\u7121\u306B\u304B\u304B\u308F\u3089\u305A\u5E38\u306BJavaScript\u3067\u8A55\u4FA1\u3057\u3001kintone\u3078\u62BC\u3057\u4E0B\u3052\u307E\u305B\u3093\u3002\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u306A\u3057\u306FkSQL\u72EC\u81EA\u306E\u90E8\u5206\u4E00\u81F4\uFF08`includes`\uFF09\u3067\u3059\u3002\u901A\u5E38\u306E\u89AA\u30EC\u30B3\u30FC\u30C9DML\u3067\u306FLIKE\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF08**\u4F8B\u5916**: v3.10.0 \u4EE5\u964D\u3001APPLY \u8907\u6570\u89AA `UPDATE` \u306E\u89AA WHERE \u3067\u306F LIKE \u3092\u4F7F\u7528\u3067\u304D\u307E\u3059\uFF1D\u5B89\u5168\u30D7\u30EC\u30D5\u30A3\u30EB\u30BF\u3067\u53D6\u5F97\u5F8C\u306B\u5143 WHERE \u3092 JS \u518D\u8A55\u4FA1\u3057\u307E\u3059\u3002\u901A\u5E38\u306E\u89AA UPDATE/DELETE \u3067\u306F KLIKE \u306E\u307F\u4F7F\u7528\u3067\u304D LIKE \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF09\u3002\u8A73\u7D30\u306F\u300CLIKE / NOT LIKE\uFF08\u90E8\u5206\u4E00\u81F4\u30FB\u9664\u5916\uFF09\u300D\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n---", uri: "ksql://language-reference/22-limitations" }, "23-ui-features": { heading: "23. UI \u6A5F\u80FD", text: '## 23. UI \u6A5F\u80FD\r\n\r\n### \u30A8\u30E9\u30FC\u30E1\u30C3\u30BB\u30FC\u30B8\r\n\r\nkintone API \u306E\u30A8\u30E9\u30FC\u306F\u308F\u304B\u308A\u3084\u3059\u304F\u8868\u793A\u3055\u308C\u307E\u3059\u3002\u30D5\u30A3\u30FC\u30EB\u30C9\u30EC\u30D9\u30EB\u306E\u30A8\u30E9\u30FC\u3082\u5C55\u958B\u3057\u3066\u8868\u793A\u3057\u307E\u3059\u3002\r\n\r\n```\r\n\u26A0 \u5165\u529B\u5185\u5BB9\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093\u3002\r\n records[0].\u9867\u5BA2\u30E9\u30F3\u30AF.value: "V"\u306F\u9078\u629E\u80A2\u306B\u3042\u308A\u307E\u305B\u3093\u3002\r\n\r\n\u26A0 \u6307\u5B9A\u3055\u308C\u305F\u30D5\u30A3\u30FC\u30EB\u30C9\uFF08\u9867\u5BA2\u30E9\u30F3\u30AF\uFF09\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002\r\n```\r\n\r\n### \u5B9F\u884C\u5C65\u6B74\r\n\r\n- \u5B9F\u884C\u3057\u305F SQL \u306F\u81EA\u52D5\u7684\u306B\u5C65\u6B74\u306B\u4FDD\u5B58\u3055\u308C\u307E\u3059\r\n- **\u30A8\u30E9\u30FC\u306B\u306A\u3063\u305F SQL \u3082\u4FDD\u5B58\u3055\u308C\u307E\u3059**\uFF08\u4FEE\u6B63\u30FB\u518D\u5B9F\u884C\u304C\u3057\u3084\u3059\u304F\u306A\u308A\u307E\u3059\uFF09\r\n- \u30AD\u30E3\u30F3\u30BB\u30EB\u3057\u305F\u5834\u5408\u306F\u4FDD\u5B58\u3055\u308C\u307E\u305B\u3093\r\n- \u300C\u5C65\u6B74 \u25BC\u300D\u30DC\u30BF\u30F3\u304B\u3089\u904E\u53BB\u306E SQL \u3092\u9078\u629E\u3057\u3066\u518D\u5B9F\u884C\u3067\u304D\u307E\u3059\r\n\r\n---', uri: "ksql://language-reference/23-ui-features" }, "24-explain": { heading: "24. EXPLAIN", text: "## 24. EXPLAIN\r\n\r\n`EXPLAIN` \u3092\u5148\u982D\u306B\u4ED8\u3051\u308B\u3068\u3001schema-aware\u306A\u5B9F\u884C\u8A08\u753B\u3092\u8868\u793A\u3057\u307E\u3059\u3002\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u3068\u3001canonical STATUS\u9806\u306B\u5FC5\u8981\u306A\u5834\u5408\u3060\u3051\u30D7\u30ED\u30BB\u30B9\u72B6\u614B\u5B9A\u7FA9\u3092\u8AAD\u307F\u307E\u3059\u3002\u30EC\u30B3\u30FC\u30C9\u53D6\u5F97\u30FB\u66F8\u304D\u8FBC\u307FAPI\u306F\u547C\u3073\u307E\u305B\u3093\u3002\r\n\r\n```sql\r\nEXPLAIN SELECT * FROM APP100 WHERE \u30B9\u30C6\u30FC\u30BF\u30B9 = '\u5B8C\u4E86'\r\nEXPLAIN UPDATE APP100 SET \u72B6\u614B = '\u5B8C\u4E86' WHERE $id = 1\r\nEXPLAIN DELETE FROM APP100 WHERE $id = 1\r\nEXPLAIN INSERT INTO APP100 (\u9867\u5BA2\u540D) VALUES ('A\u793E')\r\nEXPLAIN UPSERT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D) VALUES ('C001', 'A\u793E') ON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\nEXPLAIN REORDER APP100$\u660E\u7D30 BY \u5546\u54C1\u30B3\u30FC\u30C9 ASC WHERE _pid = 1\r\nEXPLAIN VALIDATE APP100\r\nEXPLAIN IMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D) FROM CSV customers BY NAME\r\n```\r\n\r\n### \u30B5\u30DD\u30FC\u30C8\u5BFE\u8C61\r\n\r\n- `SELECT` / `WITH` / `INSERT` / `UPDATE` / `DELETE` / `UPSERT` / `REORDER` / `VALIDATE` / `IMPORT`\r\n\r\n### \u5236\u7D04\r\n\r\n- `EXPLAIN SHOW APPS` \u306A\u3069\u3001\u4E0A\u8A18\u4EE5\u5916\u306E\u6587\u306F\u975E\u5BFE\u5FDC\u3067\u3059\r\n- \u5B9F\u30C7\u30FC\u30BF\u306E\u53D6\u5F97\u30FB\u66F4\u65B0\u306F\u884C\u3044\u307E\u305B\u3093\uFF08metadata API\u306E\u307F\uFF09\r\n- \u5BFE\u8C61\u30A2\u30D7\u30EA\u306E\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u3092\u8AAD\u3081\u308B\u6A29\u9650\u304C\u5FC5\u8981\u3067\u3059\u3002schema\u53D6\u5F97\u306B\u5931\u6557\u3057\u305F\u5834\u5408\u3001\u63A8\u5B9ASIMPLE\u3068\u3057\u3066\u6210\u529F\u3055\u305B\u305A\u5143\u306E\u8A8D\u8A3C\u30FB\u901A\u4FE1\u30A8\u30E9\u30FC\u3092\u8FD4\u3057\u307E\u3059\r\n- `order plan`\u306F`CANONICAL_LOCAL`\uFF0F`CANONICAL_REST_TOP_N`\uFF0F`KORDER_NATIVE`\u3092\u8868\u793A\u3057\u307E\u3059\r\n\r\n---", uri: "ksql://language-reference/24-explain" }, "25-batch-temp-tables": { heading: "25. \u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB", text: "## 25. \u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\r\n\r\n> **CLI\uFF08`-e` / `-f` / `--console`\uFF09\u3068 MCP\uFF08`ksql_query` / `ksql_validate` / `ksql_mutate` / `ksql_explain`\uFF09\u3067\u5229\u7528\u53EF\u80FD**\u3067\u3059\u3002\u30D7\u30E9\u30B0\u30A4\u30F3 UI \u3082\u30D0\u30C3\u30C1\u306B\u5BFE\u5FDC\u3057\uFF08DML \u3092\u542B\u3080\u30D0\u30C3\u30C1\u3082\u5B9F\u884C\u53EF\u80FD\uFF09\u3001\u6700\u5F8C\u306B\u7D50\u679C\u30BB\u30C3\u30C8\u3092\u8FD4\u3057\u305F\u6587\uFF08\u901A\u5E38\u306F\u6700\u7D42 SELECT\uFF09\u3060\u3051\u3092\u8868\u793A\u3057\u307E\u3059\u3002\u8A73\u7D30\u4ED5\u69D8\u306F [ksql_batch_temp_table_spec.md](internal/ksql_batch_temp_table_spec.md) \u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n>\r\n> **\u30EA\u30E9\u30F3\u53EF\u80FD\u306A\u5DEE\u5206\u66F4\u65B0\u30D0\u30C3\u30C1\u306E\u8A2D\u8A08\u30D1\u30BF\u30FC\u30F3**\uFF08\u30B9\u30C6\u30FC\u30BF\u30B9\u99C6\u52D5\u30FB\u4EF6\u6570\u30B2\u30FC\u30C8\u30FB\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\u30FB\u30D0\u30C3\u30C1\u5909\u6570\u306E\u6D3B\u7528\uFF09\u306F [ksql_batch_recipes.md](ksql_batch_recipes.md) \u306B\u307E\u3068\u3081\u3066\u3044\u307E\u3059\u3002\r\n\r\n### \u8907\u6587\uFF08\u30D0\u30C3\u30C1\uFF09\r\n\r\n`;` \u533A\u5207\u308A\u3067\u8907\u6570\u306E SQL \u6587\u30921\u56DE\u306E\u547C\u3073\u51FA\u3057\u3067**\u9806\u6B21**\u5B9F\u884C\u3067\u304D\u307E\u3059\uFF08\u6700\u5927 20 \u6587\uFF09\u3002\r\n\r\n```sql\r\nSELECT \u90E8\u9580 FROM APP100;\r\nSELECT \u90E8\u9580 FROM APP200;\r\n```\r\n\r\n- read-only \u6587\u306E\u307F\u306E\u30D0\u30C3\u30C1\u306F `ksql_query` / CLI / \u30D7\u30E9\u30B0\u30A4\u30F3\u304C\u305D\u306E\u307E\u307E\u5B9F\u884C\u3057\u307E\u3059\u3002**DML \u3092\u542B\u3080\u30D0\u30C3\u30C1**\u306F `ksql_mutate`\uFF08`dmlMaxRows` \u306F\u6587\u3054\u3068 + \u4EFB\u610F\u306E `dmlTotalMaxRows` \u3067\u5408\u8A08\u30AC\u30FC\u30C9\uFF09\u3001CLI `--allow-dml`\uFF08\u78BA\u8A8D\u30D7\u30ED\u30F3\u30D7\u30C8\u306F\u30D0\u30C3\u30C1\u5168\u4F53\u30671\u56DE\u3001`--yes` \u3067\u30B9\u30AD\u30C3\u30D7\uFF09\u3001\u307E\u305F\u306F\u30D7\u30E9\u30B0\u30A4\u30F3\uFF08\u6587\u3054\u3068\u306E\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0\uFF09\u3067\u5B9F\u884C\u3057\u307E\u3059\u3002DML \u30D0\u30C3\u30C1\u306F\u5E38\u306B fail-fast \u3067\u3059\r\n- SELECT-based DML\uFF08`INSERT INTO APPxxx ... SELECT` / `UPSERT INTO APPxxx ... SELECT ... ON DUPLICATE`\uFF09\u306E\u30BD\u30FC\u30B9\u306F **APP\u30FB\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30FB\u4E21\u8005\u306E\u6DF7\u5728\uFF08JOIN\u30FB\u30B5\u30D6\u30AF\u30A8\u30EA\uFF09\u306E\u3044\u305A\u308C\u3082\u6307\u5B9A\u3067\u304D\u307E\u3059**\u3002\u4EF6\u6570\u306B\u306F\u66F8\u304D\u8FBC\u307F\u524D\u306E\u78BA\u8A8D\u3067 `dmlMaxRows` \u304C\u9069\u7528\u3055\u308C\uFF08UPSERT \u306F insert + update \u306E**\u5408\u8A08**\uFF09\u3001\u8D85\u904E\u6642\u306F\u5F53\u8A72\u6587\u30BC\u30ED\u66F8\u304D\u8FBC\u307F\u3067\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\r\n- SELECT-based DML \u306E\u8AAD\u307F\u53D6\u308A\u4E0A\u9650\u306F\u30BD\u30FC\u30B9\u7A2E\u985E\u3054\u3068\u306B\u7570\u306A\u308A\u307E\u3059: **APP \u30BD\u30FC\u30B9\u306E\u8AAD\u307F\u53D6\u308A\u306F `maxRecords` \u306E\u901A\u5E38\u89E3\u6C7A\u5024\uFF08`KSQL_MAX_RECORDS` / profile \u306E `query.maxRecords`\u3001\u65E2\u5B9A 500 \u4EF6\uFF09**\uFF08\u8D85\u904E\u306F\u66F8\u304D\u8FBC\u307F\u524D\u306E\u5B89\u5168\u5074\u30A8\u30E9\u30FC\u3002JOIN \u306E APP \u5074\u3082\u540C\u69D8\u3002`dmlMaxRows` \u306F\u5F71\u97FF\u884C\u6570\u30AC\u30FC\u30C9\u5C02\u7528\u3067\u8AAD\u307F\u53D6\u308A\u3092\u7D5E\u308A\u307E\u305B\u3093\uFF09\u3001**\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306F\u5B9F\u4F53\u5316\u4E0A\u9650 \u65E2\u5B9A 10,000 \u884C\uFF08`tempTableMaxRows` \u3067\u5909\u66F4\u53EF\uFF09**\u3002UPSERT \u7CFB\u3067\u306F\u66F8\u304D\u8FBC\u307F\u5148\u30A2\u30D7\u30EA\u3078\u306E\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u7167\u5408\u8AAD\u307F\u53D6\u308A\u304C**\u30BD\u30FC\u30B9\u7A2E\u985E\u306B\u95A2\u308F\u3089\u305A**\u767A\u751F\u3057\u307E\u3059\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306B\u5B9F\u4F53\u5316\u3057\u3066\u3082\u56DE\u907F\u3055\u308C\u307E\u305B\u3093\uFF09\r\n- \u5B9F\u884C\u524D\u306B\u5168\u6587\u3092\u691C\u8A3C\u3057\u30011\u6587\u3067\u3082\u4E0D\u6B63\u306A\u3089\u30D0\u30C3\u30C1\u5168\u4F53\u3092\u62D2\u5426\u3057\u307E\u3059\uFF08validate-all-first\uFF09\r\n- \u65E2\u5B9A\u306F fail-fast\uFF08\u30A8\u30E9\u30FC\u6587\u4EE5\u964D\u306F\u30B9\u30AD\u30C3\u30D7\uFF09\u3002`--continue-on-error`\uFF08CLI\uFF09/ `continueOnError`\uFF08MCP\uFF09\u3067\u30A8\u30E9\u30FC\u5F8C\u306E\u7D9A\u884C\u3092\u9078\u3079\u307E\u3059\r\n- \u7D50\u679C\u306F\u6587\u3054\u3068\u306B `success` / `error` / `skipped` \u3068\u3057\u3066\u5831\u544A\u3055\u308C\u307E\u3059\r\n\r\n### \u4E00\u6642\u30C6\u30FC\u30D6\u30EB\r\n\r\n`CREATE TEMP TABLE #\u540D\u524D AS SELECT ...` \u3067 SELECT \u7D50\u679C\u3092\u30D0\u30C3\u30C1\u5185\u306B\u5B9F\u4F53\u5316\u3057\u3001\u5F8C\u7D9A\u306E\u6587\u304B\u3089 `FROM` / `JOIN` / \u30B5\u30D6\u30AF\u30A8\u30EA\u3067\u53C2\u7167\u3067\u304D\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u76F8\u95A2\u30B5\u30D6\u30AF\u30A8\u30EA\u306E\u56DE\u907F\u4F8B\r\nCREATE TEMP TABLE #latest AS\r\nSELECT \u9867\u5BA2ID, MAX(\u53D7\u6CE8\u65E5) AS \u6700\u65B0\u53D7\u6CE8\u65E5\r\nFROM APP300\r\nGROUP BY \u9867\u5BA2ID;\r\n\r\nSELECT a.\u9867\u5BA2\u540D, t.\u6700\u65B0\u53D7\u6CE8\u65E5\r\nFROM APP100 a\r\nINNER JOIN #latest t ON a.\u9867\u5BA2ID = t.\u9867\u5BA2ID;\r\n```\r\n\r\n> **\u6CE8\u610F**: \u4E0A\u8A18\u306E `MAX(\u53D7\u6CE8\u65E5)` \u306F\u3001`APP300` \u306E\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u304B\u3089 DATE \u578B\u3092\u89E3\u6C7A\u3057\u3066\u6700\u65B0\u65E5\u3092\u8FD4\u3057\u307E\u3059\u3002\u4E00\u6642\u30C6\u30FC\u30D6\u30EB/CTE\u3078\u578B\u30E1\u30BF\u304C\u4F1D\u64AD\u3059\u308B\u305F\u3081\u3001`SELECT MAX(\u6700\u65B0\u53D7\u6CE8\u65E5) FROM #latest` \u306E\u3088\u3046\u306A\u518D\u96C6\u7D04\u3067\u3082\u65E5\u6642\u306E\u8F9E\u66F8\u9806\u6BD4\u8F03\u3092\u7DAD\u6301\u3057\u307E\u3059\uFF08\u524D\u63B2\u306E\u96C6\u8A08\u95A2\u6570\u306E\u6BD4\u8F03\u898F\u5247\u3092\u53C2\u7167\uFF09\u3002\r\n\r\n| \u898F\u5247 | \u5185\u5BB9 |\r\n|---|---|\r\n| \u540D\u524D | `#` + \u8B58\u5225\u5B50\uFF08\u4F8B: `#temp` / `#\u96C6\u8A08`\uFF09\u3002`#` \u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\u306E\u5148\u982D\u306E\u307F\u3067\u6709\u52B9\u3002\u30A8\u30A4\u30EA\u30A2\u30B9\u306B\u306F\u4F7F\u7528\u4E0D\u53EF |\r\n| \u5BFF\u547D | **\u30D0\u30C3\u30C1\u5185\u306E\u307F**\u3002\u547C\u3073\u51FA\u3057\u7D42\u4E86\u3067\u81EA\u52D5\u7834\u68C4\uFF08\u547C\u3073\u51FA\u3057\u3092\u307E\u305F\u3050\u53C2\u7167\u306F\u4E0D\u53EF\uFF09 |\r\n| \u7834\u68C4 | `DROP TEMP TABLE #\u540D\u524D`\uFF08\u4E3B\u306B\u30E1\u30E2\u30EA\u306E\u65E9\u671F\u89E3\u653E\u7528\u3002DROP \u5F8C\u306E\u540C\u540D\u518D CREATE \u306F\u53EF\uFF09 |\r\n| \u4E0A\u9650 | \u540C\u6642 16 \u500B\u30FB1\u500B\u3042\u305F\u308A\u65E2\u5B9A 10,000 \u884C\uFF08\u8D85\u904E\u306F\u5E38\u306B\u30A8\u30E9\u30FC\uFF09\u3002\u884C\u6570\u4E0A\u9650\u306F `tempTableMaxRows` \u3067\u5909\u66F4\u53EF\u80FD\uFF08MCP \u30C4\u30FC\u30EB\u5F15\u6570 / CLI `--temp-table-max-rows` / env `KSQL_TEMP_TABLE_MAX_ROWS` / profile `query.tempTableMaxRows` / \u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u300C\u2699 \u30AA\u30D7\u30B7\u30E7\u30F3 \u2192 \u53D6\u5F97\u300D\u306E\u300C\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u9650(\u884C)\u300D\u3002\u7A7A\u6B04 = \u65E2\u5B9A\uFF09\u3002\u5909\u66F4\u3057\u3066\u3082\u8D85\u904E\u6642\u306F truncate \u3055\u308C\u305A\u5E38\u306B\u30A8\u30E9\u30FC |\r\n| DML | \u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3078\u306E INSERT / UPDATE / DELETE \u306F\u975E\u5BFE\u5FDC |\r\n| \u5B9F\u884C | \u53C2\u7167\u306F\u5E38\u306B\u30A4\u30F3\u30E1\u30E2\u30EA FULL_SCAN\uFF08kintone \u30AF\u30A8\u30EA\u3078\u306E WHERE \u30D7\u30C3\u30B7\u30E5\u30C0\u30A6\u30F3\u306F\u52B9\u304B\u306A\u3044\uFF09 |\r\n\r\n### \u30B3\u30F3\u30BD\u30FC\u30EB\uFF08`--console`\uFF09\u3067\u306E\u5165\u529B\r\n\r\n- \u5358\u6587\u306F\u5F93\u6765\u3069\u304A\u308A\u884C\u672B `;` \u3067\u5B9F\u884C\u3055\u308C\u307E\u3059\r\n- `CREATE TEMP TABLE` \u3067\u59CB\u307E\u308B\u5165\u529B\u306F**\u30D0\u30C3\u30C1\u69CB\u7BC9\u30E2\u30FC\u30C9**\u306B\u306A\u308A\u3001`;` \u3067\u306F\u5B9F\u884C\u3055\u308C\u305A **`:run`** \u3067\u30D0\u30C3\u30D5\u30A1\u5168\u4F53\u3092\u30D0\u30C3\u30C1\u5B9F\u884C\u3057\u307E\u3059\uFF08\u7834\u68C4\u306F `:clear`\uFF09\r\n\r\n### \u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306E DML \u30D0\u30C3\u30C1\r\n\r\n\u30D7\u30E9\u30B0\u30A4\u30F3 UI \u3067\u3082 DML \u3092\u542B\u3080\u30D0\u30C3\u30C1\u3092\u5B9F\u884C\u3067\u304D\u307E\u3059\u3002\r\n\r\n- DML \u6587\u306F**\u6587\u3054\u3068\u306E\u78BA\u8A8D\u30C0\u30A4\u30A2\u30ED\u30B0**\uFF08\u6587\u756A\u53F7 `[N/M]`\u30FB\u66F8\u304D\u8FBC\u307F\u5148\u30A2\u30D7\u30EA\u30FB\u78BA\u5B9A\u4EF6\u6570\u4ED8\u304D\uFF09\u3067\u66F8\u304D\u8FBC\u307F\u76F4\u524D\u306B\u78BA\u8A8D\u3057\u307E\u3059\r\n- `INSERT INTO ... VALUES` \u306F\u9759\u7684\u306B\u4EF6\u6570\u304C\u78BA\u5B9A\u3059\u308B\u305F\u3081\u3001**\u30D0\u30C3\u30C1\u5B9F\u884C\u524D**\u306B\u307E\u3068\u3081\u3066\u78BA\u8A8D\u3057\u307E\u3059\uFF08\u30AD\u30E3\u30F3\u30BB\u30EB\u6642\u306F 1 \u6587\u3082\u5B9F\u884C\u3055\u308C\u307E\u305B\u3093\uFF09\r\n- \u5B9F\u884C\u6642\u78BA\u8A8D\u3092\u30AD\u30E3\u30F3\u30BB\u30EB\u3057\u305F\u5834\u5408\u306F\u6587 `[N/M]` \u3067\u4E2D\u65AD\u3057\u3001\u305D\u308C\u4EE5\u524D\u306E\u6587\u306E\u5B9F\u884C\u7D50\u679C\u306F\u53CD\u6620\u6E08\u307F\u306E\u307E\u307E\u6B8B\u308A\u307E\u3059\uFF08\u30C8\u30E9\u30F3\u30B6\u30AF\u30B7\u30E7\u30F3\u306A\u3057\uFF09\r\n- \u6210\u529F\u3057\u305F DML \u6587\u306E\u5F71\u97FF\u4EF6\u6570\u306F\u30B5\u30DE\u30EA\u884C\uFF08`[N] \u30BF\u30A4\u30D7: inserted=... updated=...`\uFF09\u3068\u3057\u3066\u7D50\u679C\u306E\u4E0A\u306B\u8868\u793A\u3055\u308C\u307E\u3059\r\n- DML \u3092\u542B\u3080\u5B9F\u884C\uFF08\u5358\u6587\u30FB\u30D0\u30C3\u30C1\u3068\u3082\uFF09\u3067\u306F\u53D6\u5F97\u4E0A\u9650\u5230\u9054\u6642\u306E\u52D5\u4F5C\u304C UI \u8A2D\u5B9A\u306B\u95A2\u308F\u3089\u305A **error \u306B\u56FA\u5B9A**\u3055\u308C\u307E\u3059\uFF08truncate \u3060\u3068 SELECT-based DML \u306E\u30BD\u30FC\u30B9\u8AAD\u307F\u53D6\u308A\u304C\u9ED9\u3063\u3066\u5207\u308A\u6368\u3066\u3089\u308C\u3001\u90E8\u5206\u66F8\u304D\u8FBC\u307F\u306B\u306A\u308B\u305F\u3081\uFF09\r\n\r\n### \u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306E\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u9650\u6307\u5B9A\r\n\r\n\u300C\u2699 \u30AA\u30D7\u30B7\u30E7\u30F3 \u2192 \u53D6\u5F97\u300D\u306E\u300C\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u9650(\u884C)\u300D\u3067\u5B9F\u884C\u3054\u3068\u306B\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08\u7A7A\u6B04 = \u65E2\u5B9A 10,000\u3002\u8D85\u904E\u306F\u300C\u6253\u3061\u5207\u3063\u3066\u7D9A\u884C\u300D\u8A2D\u5B9A\u3067\u3082\u5E38\u306B\u30A8\u30E9\u30FC\uFF09\u3002\u4E00\u89A7\u30DA\u30FC\u30B8\u306E\u5165\u529B\u5024\u306F localStorage \u306B\u4FDD\u5B58\u3055\u308C\u3001SQL \u5C65\u6B74\u306B\u3082\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\u3068\u3057\u3066\u6B8B\u308A\u307E\u3059\u3002\r\n\r\n**\u30EC\u30B3\u30FC\u30C9\uFF08\u4FDD\u5B58SQL\uFF09\u3054\u3068\u306B\u5024\u3092\u4FDD\u6301\u3059\u308B**\u306B\u306F\u3001\u4FDD\u5B58SQL\u30A2\u30D7\u30EA\u306B\u4EFB\u610F\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u8FFD\u52A0\u3057\u307E\u3059\u3002\u30EC\u30B3\u30FC\u30C9\u7DE8\u96C6\u753B\u9762\u3067\u306E\u5165\u529B\u5024\u306E\u4FDD\u6301\u3068\u3001\u4E00\u89A7\u30DA\u30FC\u30B8\u3067\u30EC\u30B3\u30FC\u30C9\u3092\u9078\u629E\u3057\u305F\u3068\u304D\u306E\u30D1\u30CD\u30EB\u53CD\u6620\u306B\u4F7F\u308F\u308C\u307E\u3059\u3002\r\n\r\n#### \u65E2\u5B58\u30A2\u30D7\u30EA\u3078\u306E\u300C\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u9650\u884C\u300D\u30D5\u30A3\u30FC\u30EB\u30C9\u8FFD\u52A0\u624B\u9806\r\n\r\nv1.11.0 \u306E\u30A2\u30D7\u30EA\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\uFF08`ksql-app-template-v1.11.0.zip`\uFF09\u306B\u306F\u8FFD\u52A0\u6E08\u307F\u3067\u3059\u3002\u305D\u308C\u4EE5\u524D\u306E\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u304B\u3089\u4F5C\u6210\u3057\u305F\u65E2\u5B58\u30A2\u30D7\u30EA\u306B\u306F\u3001\u6B21\u306E\u624B\u9806\u3067\u8FFD\u52A0\u3057\u307E\u3059\u3002\r\n\r\n1. \u4FDD\u5B58SQL\u30A2\u30D7\u30EA\u306E **\u8A2D\u5B9A \u2192 \u30D5\u30A9\u30FC\u30E0** \u3092\u958B\u304F\r\n2. **\u6570\u5024** \u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u914D\u7F6E\u3059\u308B\uFF08\u5834\u6240\u306F\u4EFB\u610F\u3002\u300C\u6700\u5927\u53D6\u5F97\u4EF6\u6570\u300D\u306E\u8FD1\u304F\u3092\u63A8\u5968\uFF09\r\n3. \u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u8A2D\u5B9A\u3092\u958B\u304D\u3001\u6B21\u306E\u3068\u304A\u308A\u5165\u529B\u3057\u3066\u4FDD\u5B58\u3059\u308B\r\n - \u30D5\u30A3\u30FC\u30EB\u30C9\u540D: \u4EFB\u610F\uFF08\u4F8B: `\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u9650\u884C`\uFF09\r\n - **\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9: `\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u4E0A\u9650\u884C`\uFF08\u5B8C\u5168\u4E00\u81F4\u30FB\u5FC5\u9808\uFF09**\r\n4. **\u30A2\u30D7\u30EA\u3092\u66F4\u65B0** \u3059\u308B\r\n\r\n- \u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u8FFD\u52A0\u3057\u306A\u304F\u3066\u3082\u5F93\u6765\u3069\u304A\u308A\u52D5\u4F5C\u3057\u307E\u3059\uFF08\u30EC\u30B3\u30FC\u30C9\u3054\u3068\u306E\u4FDD\u6301\u304C\u52B9\u304B\u306A\u3044\u3060\u3051\u3067\u3001\u30D1\u30CD\u30EB\u3067\u306E\u5B9F\u884C\u3054\u3068\u6307\u5B9A\u30FBlocalStorage\u30FB\u5C65\u6B74\u306F\u4F7F\u3048\u307E\u3059\uFF09\r\n- \u30EC\u30B3\u30FC\u30C9\u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u304C**\u7A7A\u6B04**\u306E\u5834\u5408\u306F\u300C\u65E2\u5B9A 10,000 \u3067\u5B9F\u884C\u3059\u308B\u300D\u3068\u3044\u3046\u660E\u793A\u6307\u5B9A\u306B\u306A\u308A\u307E\u3059\uFF08\u30EC\u30B3\u30FC\u30C9\u9078\u629E\u6642\u306B\u30D1\u30CD\u30EB\u3082\u7A7A\u6B04 = \u65E2\u5B9A\u3078\u623B\u308A\u307E\u3059\uFF09\r\n\r\n### \u30D0\u30C3\u30C1\u5909\u6570\uFF08`SET @var`\uFF09\r\n\r\n\u30D0\u30C3\u30C1\u5185\u3067\u5024\u3092\u4E00\u5EA6\u5B9A\u7FA9\u3057\u3001\u5F8C\u7D9A\u306E\u6587\u304B\u3089 `@\u540D\u524D` \u3067\u53C2\u7167\u3067\u304D\u307E\u3059\u3002**\u6642\u523B\u306E\u56FA\u5B9A**\u30FB**\u30D0\u30C3\u30C1 ID**\u30FB**\u6761\u4EF6\u5024\u306E\u5171\u901A\u5316\uFF08DRY\uFF09** \u306B\u4F7F\u3044\u307E\u3059\u3002\r\n\r\n```sql\r\nSET @now = NOW(); -- \u30D0\u30C3\u30C1\u5185\u3067\u6642\u523B\u3092\u56FA\u5B9A\uFF08ISO \u6587\u5B57\u5217\uFF09\r\nSET @batch_id = NOW(); -- \u30D0\u30C3\u30C1 ID \u3068\u3057\u3066\u5229\u7528\r\n\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u51E6\u7406\u6E08', \u51E6\u7406\u65E5\u6642 = @now, \u30D0\u30C3\u30C1ID = @batch_id\r\nWHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u672A\u51E6\u7406';\r\n```\r\n\r\n\u4E8B\u5F8C\u691C\u8A3C\u304C `WHERE \u30D0\u30C3\u30C1ID = @batch_id` \u306E\u5B8C\u5168\u4E00\u81F4\u306B\u306A\u308A\u3001`\u51E6\u7406\u65E5\u6642 >= TODAY()` \u306E\u3088\u3046\u306A\u8FD1\u4F3C\u6761\u4EF6\u304C\u4E0D\u8981\u306B\u306A\u308A\u307E\u3059\u3002\r\n\r\n| \u898F\u5247 | \u5185\u5BB9 |\r\n|---|---|\r\n| \u69CB\u6587 | `SET @\u540D\u524D = <\u5F0F>`\u3002\u5F0F\u306F**\u30EA\u30C6\u30E9\u30EB**\uFF08\u6587\u5B57\u5217\u30FB\u6570\u5024\uFF09\u30FB**\u95A2\u6570**\uFF08`NOW()` / `TODAY()` / \u6587\u5B57\u5217\u30FB\u6570\u5024\u95A2\u6570\uFF09\u30FB**\u6570\u5024\u7B97\u8853**\u30FB**\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA**\uFF08`(SELECT ...)`\u3002\u4E0B\u8A18\uFF09\u30FB**\u6587\u5B57\u5217\u914D\u5217**\uFF08`['A','B']` / `[]`\uFF09\u3002`@\u540D\u524D` \u306F\u82F1\u5B57\u304B `_` \u3067\u59CB\u307E\u308A\u82F1\u6570\u5B57\u30FB`_`\u300164 \u6587\u5B57\u4EE5\u5185\u3002\u5927\u6587\u5B57\u5C0F\u6587\u5B57\u306F\u533A\u5225\u3057\u306A\u3044 |\r\n| \u53C2\u7167\u3067\u304D\u308B\u4F4D\u7F6E | \u30B9\u30AB\u30E9\u30FC\u306F **WHERE \u53F3\u8FBA\u306E\u5024** / **UPDATE \u306E SET \u5024** / **ASSERT \u306E\u30AA\u30DA\u30E9\u30F3\u30C9** / **IN \u30EA\u30B9\u30C8\u306E\u8981\u7D20**\uFF08`IN (@a,@b)`\uFF09/ **SELECT \u5B9A\u6570\u5217**\uFF08`@x AS alias`\u3001AS \u5FC5\u9808\uFF09\u3002\u914D\u5217\u306F\u5168\u6761\u4EF6\u4F4D\u7F6E\u306E\u30AB\u30C3\u30B3\u7121\u3057 **`IN @list` / `NOT IN @list`** \u3060\u3051 |\r\n| \u8A55\u4FA1 | `SET` \u306E\u5B9F\u884C\u6642\u306B**\u4E00\u5EA6\u3060\u3051**\u8A55\u4FA1\u3057\u3001\u4EE5\u5F8C\u306F\u5B9A\u6570\uFF08`SET @now = NOW()` \u306F\u30D0\u30C3\u30C1\u5185\u3067\u540C\u3058\u6642\u523B\u306B\u56FA\u5B9A\u3002`NOW()` \u81EA\u4F53\u306E\u610F\u5473\u306F\u5909\u308F\u308A\u307E\u305B\u3093\uFF09 |\r\n| \u578B | \u4EE3\u5165\u5024\u304B\u3089 **string / number / string array** \u3092\u6C7A\u5B9A\u3002scalar/array \u306E\u53C2\u7167\u4F4D\u7F6E\u9055\u53CD\u306F\u5168\u30D0\u30C3\u30C1\u5B9F\u884C\u524D\u306B\u62D2\u5426\u3002\u6BD4\u8F03\u306E\u578B\u898F\u5247\u306F WHERE \u3068\u540C\u4E00 |\r\n| \u30B9\u30B3\u30FC\u30D7 | **1 \u30D0\u30C3\u30C1\u5185\u306E\u307F**\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3068\u540C\u3058\u5BFF\u547D\uFF09\u3002\u30D0\u30C3\u30C1\u3092\u307E\u305F\u304C\u306A\u3044 |\r\n| \u30D0\u30C3\u30C1\u5FC5\u9808 | **2 \u6587\u4EE5\u4E0A\u306E\u30D0\u30C3\u30C1\u3067\u306E\u307F\u4F7F\u7528\u53EF**\u3002\u5358\u6587\u306E `SET`\u30FB\u5358\u6587\u3067\u306E `@\u53C2\u7167` \u306F\u30A8\u30E9\u30FC |\r\n| \u9759\u7684\u691C\u67FB | **\u672A\u5B9A\u7FA9\u53C2\u7167\u30FB\u524D\u65B9\u53C2\u7167\u30FB\u518D\u4EE3\u5165\u306F\u30A8\u30E9\u30FC**\uFF08\u5B9F\u884C\u524D\u306B\u691C\u51FA\uFF09\u3002\u672A\u4F7F\u7528\u306F\u8B66\u544A\u3002`SET` \u306E\u8A55\u4FA1\u306B\u5931\u6557\u3057\u305F\u5834\u5408\u306F `continueOnError` \u306B\u95A2\u308F\u3089\u305A\u30D0\u30C3\u30C1\u3092\u505C\u6B62 |\r\n| \u4E0A\u9650 | \u5909\u6570\u306E\u9632\u5FA1\u4E0A\u9650\u306F **64 \u500B**\u3002\u305F\u3060\u3057\u30D0\u30C3\u30C1\u5168\u4F53\u306E**\u6700\u5927 20 \u6587**\uFF08\xA725 \u5192\u982D\uFF09\u304C\u5148\u306B\u52B9\u304F\u305F\u3081\u3001`SET` \u3082 1 \u6587\u305A\u3064\u6570\u3048\u308B\u73FE\u72B6\u306E\u5B9F\u52B9\u4E0A\u9650\u306F **20 \u500B\u4EE5\u4E0B** |\r\n| \u6F14\u7B97 | \u5F0F\u5185\u306E `+` \u306F**\u6570\u5024\u52A0\u7B97**\u3002\u6587\u5B57\u5217\u9023\u7D50\u306F `CONCAT()` \u3092\u4F7F\u3046\u3002**SET \u306E\u53F3\u8FBA\u304B\u3089\u5225\u306E\u5909\u6570\u306F\u53C2\u7167\u3067\u304D\u307E\u305B\u3093**\uFF08`SET @b = @a + 1` \u306F\u4E0D\u53EF\uFF09 |\r\n| \u675F\u7E1B | \u5024\u3068\u3057\u3066\u30D0\u30A4\u30F3\u30C9\uFF08\u6587\u5B57\u5217\u9023\u7D50\u3067\u306F\u306A\u3044\uFF09\u305F\u3081\u3001**SQL \u30A4\u30F3\u30B8\u30A7\u30AF\u30B7\u30E7\u30F3\u306F\u767A\u751F\u3057\u307E\u305B\u3093**\u3002\u5909\u6570\u306B\u5165\u308B\u306E\u306F\u5024\u306E\u307F\u3067\u3001\u30A2\u30D7\u30EA ID\u30FB\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u30FB\u6F14\u7B97\u5B50\u306A\u3069\u8B58\u5225\u5B50\u306E\u30D1\u30E9\u30E1\u30FC\u30BF\u5316\u306F\u3067\u304D\u307E\u305B\u3093 |\r\n\r\n#### \u30B9\u30AB\u30E9\u30FC\u5909\u6570\u306E\u914D\u7F6E\u8A73\u7D30\r\n\r\n\u4E0A\u306E\u300C\u53C2\u7167\u3067\u304D\u308B\u4F4D\u7F6E\u300D\u306F\u6982\u8981\u3067\u3059\u3002\u914D\u7F6E\u306E\u6587\u6CD5\u5883\u754C\u306F\u6B21\u306E\u8868\u3092\u6B63\u3068\u3057\u307E\u3059\u3002ID \u306F parser \u3068 batch analyzer \u306E\u7279\u6027\u5316\u30C6\u30B9\u30C8\u306B\u4E00\u5BFE\u4E00\u3067\u5BFE\u5FDC\u3057\u307E\u3059\u3002\r\n\r\n| ID | \u4F7F\u3048\u308B\u914D\u7F6E | \u5883\u754C |\r\n|---|---|---|\r\n| A01 | WHERE \u306E\u6BD4\u8F03\u53F3\u8FBA | `\u5217 >= @x` \u306E\u3088\u3046\u306B\u53F3\u8FBA\u306E\u76F4\u63A5\u5024\u3068\u3057\u3066\u4F7F\u3048\u308B\u3002VALIDATE WHERE\u3001APPLY PATCH/REMOVE WHERE \u3082\u540C\u3058\u6761\u4EF6\u6587\u6CD5\u3092\u4F7F\u3046 |\r\n| A02 | HAVING \u306E\u6BD4\u8F03\u53F3\u8FBA | \u96C6\u7D04\u7D50\u679C\u3068\u306E\u6BD4\u8F03\u53F3\u8FBA\u306B\u4F7F\u3048\u308B |\r\n| A03 | CHECK WHEN \u6761\u4EF6 | \u6BD4\u8F03\u53F3\u8FBA\u306B\u4F7F\u3048\u308B\u3002CHECK \u306E\u8A55\u4FA1\u884C\u306F \xA717.3 \u3092\u53C2\u7167 |\r\n| A04 | CASE / IF \u6761\u4EF6 | \u6761\u4EF6\u5185\u306E\u6BD4\u8F03\u53F3\u8FBA\u306B\u4F7F\u3048\u308B |\r\n| A05 | KLIKE \u53F3\u8FBA | `\u5217 KLIKE @x` / `\u5217 NOT KLIKE @x` \u306E\u30D1\u30BF\u30FC\u30F3\u5024\u306B\u4F7F\u3048\u308B |\r\n| A06 | IN \u30EA\u30B9\u30C8\u8981\u7D20 | \u30B9\u30AB\u30E9\u30FC\u5909\u6570\u3092 `IN (@a, @b)` \u306E\u8981\u7D20\u306B\u4F7F\u3048\u308B |\r\n| A07 | \u30AB\u30C3\u30B3\u7121\u3057 IN | \u6587\u5B57\u5217\u914D\u5217\u5909\u6570\u3060\u3051\u3092 `IN @list` / `NOT IN @list` \u306B\u4F7F\u3048\u308B |\r\n| A08 | SELECT \u5B9A\u6570\u5217 | `SELECT @x AS alias`\uFF08AS \u5FC5\u9808\uFF09\u3067\u30B9\u30AB\u30E9\u30FC\u5024\u3092\u5217\u3068\u3057\u3066\u5B9F\u4F53\u5316\u3067\u304D\u308B |\r\n| A09 | IMPORT SELECT \u5C04\u5F71 | IMPORT \u306E SELECT \u5C04\u5F71\u3067\u3082 `@x AS alias`\uFF08AS \u5FC5\u9808\uFF09\u3092\u4F7F\u3048\u308B |\r\n| A10 | UPDATE SET \u5024 | \u901A\u5E38 UPDATE \u306E SET \u53F3\u8FBA\u306E\u76F4\u63A5\u5024\u306B\u4F7F\u3048\u308B |\r\n| A11 | UPDATE FROM SET \u5024 | UPDATE FROM \u306E SET \u53F3\u8FBA\u306E\u76F4\u63A5\u5024\u306B\u3082\u4F7F\u3048\u308B |\r\n| A12 | ASSERT \u30AA\u30DA\u30E9\u30F3\u30C9 | \u6BD4\u8F03\u30FBBETWEEN \u306E\u76F4\u63A5\u30AA\u30DA\u30E9\u30F3\u30C9\u306B\u4F7F\u3048\u308B |\r\n| A13 | SET \u306E\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u5185 | \u5148\u884C\u5909\u6570\u3092 `(SELECT ... WHERE \u5217 = @a)` \u306E\u3088\u3046\u306B\u53C2\u7167\u3067\u304D\u308B\u3002\u5916\u5074\u306E SET \u5F0F\u3068\u306F\u5225\u6271\u3044 |\r\n\r\n| ID | \u4F7F\u3048\u306A\u3044\u914D\u7F6E | \u5883\u754C |\r\n|---|---|---|\r\n| R01 | VALUES \u306E\u76F4\u63A5\u8981\u7D20 | INSERT / UPSERT / APPEND \u306E `VALUES (@x)` \u306F\u4E0D\u53EF\u3002VALUES \u304C\u53D7\u7406\u3059\u308B CASE / IF \u306E\u5185\u90E8\u3067\u306F\u6761\u4EF6\u30FB\u5F0F\u306B\u5909\u6570\u304C\u5165\u308A\u5F97\u308B |\r\n| R02 | \u4EF6\u6570\u30FB\u4F4D\u7F6E\u3092\u8868\u3059\u56FA\u5B9A\u6570\u5024\u53E5 | `LIMIT @n` / `OFFSET @n` \u306F\u4E0D\u53EF\u3002EXPECT ROWS / REJECT LIMIT \u3082\u5909\u6570\u5316\u3067\u304D\u306A\u3044 |\r\n| R03 | \u6761\u4EF6\u5DE6\u8FBA\u30FB\u69CB\u9020\u4F4D\u7F6E | `@x = \u5217` \u306F\u4E0D\u53EF\u3002GROUP BY / ORDER BY\u3001\u30A2\u30D7\u30EA ID\u30FB\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u30FB\u6F14\u7B97\u5B50\u306A\u3069\u306E\u8B58\u5225\u5B50\u4F4D\u7F6E\u306B\u3082\u7F6E\u3051\u306A\u3044 |\r\n| R04 | \u5916\u5074\u306E SET / DECLARE \u5F0F | `SET @b = @a / 2` \u3068 `DECLARE @b = @a` \u306F\u4E0D\u53EF\u3002A13 \u306E SET \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3060\u3051\u304C\u5148\u884C\u5909\u6570\u53C2\u7167\u306E\u4F8B\u5916 |\r\n| R05 | ASCII \u898F\u5247\u5916\u306E\u5909\u6570\u540D | \u5909\u6570\u540D\u306F `@[A-Za-z_][A-Za-z0-9_]{0,63}`\uFF08\u6700\u5927 64 \u6587\u5B57\uFF09\u3067\u3001\u540D\u524D\u306F\u5C0F\u6587\u5B57\u3078\u6B63\u898F\u5316\u3055\u308C\u308B\u3002`@max\u91D1\u984D` \u306F `@max` \u3068 `\u91D1\u984D` \u306E 2 \u30C8\u30FC\u30AF\u30F3\u306B\u5206\u304B\u308C\u3001\u5909\u6570\u540D\u3068\u3057\u3066\u53D7\u7406\u3055\u308C\u306A\u3044 |\r\n\r\n\u5909\u6570\u304B\u3089\u76F4\u63A5\u59CB\u307E\u308B\u4E00\u822C\u7B97\u8853\u5F0F\u306F\u3001\u6BD4\u8F03\u53F3\u8FBA\u30FBASSERT\u30FB\u5358\u72EC SELECT \u5909\u6570\u5217\u306E\u5C02\u7528\u5206\u5C90\u3067\u306F\u4F7F\u3048\u307E\u305B\u3093\uFF08\u4F8B: `\u91D1\u984D >= @avg / 2`\uFF09\u3002B38 \u306E\u4E00\u822C\u30B9\u30AB\u30E9\u30FC\u5F0F\u3078\u5165\u308B\u95A2\u6570\u5F15\u6570\u3084 `||` \u9023\u7D50\u3067\u306F\u3001\u5909\u6570\u3092\u7B97\u8853\u306B\u53C2\u52A0\u3055\u305B\u3089\u308C\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\r\n\r\n\u6D3E\u751F\u5024\u306F\u5143\u306E SET \u306E\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u540C\u6642\u306B\u8A08\u7B97\u3059\u308B\uFF08`SET @half = (SELECT AVG(\u91D1\u984D)/2 FROM \u2026)`\uFF09\u304B\u3001\u6761\u4EF6\u5074\u3092\u5909\u5F62\u3059\u308B\uFF08`\u91D1\u984D * 2 >= @avg`\uFF09\u3002\u65E2\u5B58\u5909\u6570\u304B\u3089\u5225\u306E SET \u5909\u6570\u3092\u76F4\u63A5\u5C0E\u51FA\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u306A\u3044\u3002VALUES \u306B\u5024\u3092\u5165\u308C\u305F\u3044\u5834\u5408\u306F temp \u30C6\u30FC\u30D6\u30EB\uFF0B`@x AS \u5217`\uFF08AS \u5FC5\u9808\uFF09\u3067\u5B9F\u4F53\u5316\u3059\u308B\u3002\r\n\r\n#### \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u4EE3\u5165 `SET @x = (SELECT ...)`\r\n\r\n`SET` \u306E\u53F3\u8FBA\u306B**\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA**\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002**\u4EF6\u6570\u30B2\u30FC\u30C8\u306E DRY \u5316**\u304C\u4E3B\u7528\u9014\u3067\u3059\u3002\r\n\r\n```sql\r\nSET @cnt = (SELECT COUNT(*) FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406'));\r\nASSERT @cnt BETWEEN 0 AND 10000;\r\nUPDATE APP100 SET \u5BFE\u8C61\u4EF6\u6570\u30E1\u30E2 = @cnt WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n```\r\n\r\n| \u898F\u5247 | \u5185\u5BB9 |\r\n|---|---|\r\n| \u8A55\u4FA1 | `SET` \u306E\u5B9F\u884C\u6642\u306B**\u4E00\u5EA6\u3060\u3051**\u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u5B9F\u884C\u3057\u3001\u4EE5\u5F8C\u306F\u5B9A\u6570\uFF08\u540C\u3058\u5909\u6570\u3092\u8907\u6570\u6587\u3067\u53C2\u7167\u3057\u3066\u3082\u518D\u5B9F\u884C\u3057\u306A\u3044\uFF09 |\r\n| \u30B9\u30AB\u30E9\u30FC\u4FDD\u8A3C | \u30B5\u30D6\u30AF\u30A8\u30EA\u306F**\u5FC5\u305A 1 \u884C 1 \u5217**\u30020 \u884C\u30FB\u8907\u6570\u884C\u30FB\u8907\u6570\u5217\u306F\u30A8\u30E9\u30FC\u3002\u660E\u793A\u5217\u3067 2 \u5217\u4EE5\u4E0A\u306F\u30D1\u30FC\u30B9\u6642\u3001`SELECT *` \u7B49\u306F\u5B9F\u884C\u6642\u306B\u691C\u8A3C\u3002\u203B **GROUP BY \u306A\u3057\u306E\u96C6\u8A08\u306F 0 \u4EF6\u3067\u3082 1 \u884C\uFF08`COUNT` \u306F `0`\uFF09** \u3092\u8FD4\u3059\uFF08\xA78\uFF09\u305F\u3081 `COUNT(*)` \u4EF6\u6570\u53D6\u5F97\u306F 0 \u4EF6\u3067\u3082\u6210\u7ACB |\r\n| \u53C2\u7167 | \u30B5\u30D6\u30AF\u30A8\u30EA\u306F**\u5148\u884C\u3057\u3066\u4F5C\u6210\u3057\u305F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB**\u30FB**\u5148\u884C\u3057\u3066\u5B9A\u7FA9\u3057\u305F\u5909\u6570**\uFF08`(SELECT ... WHERE k < @prev)`\uFF09\u3092\u53C2\u7167\u53EF\u3002\u672A\u5B9A\u7FA9\u30FB\u524D\u65B9\u53C2\u7167\u306F\u5B9F\u884C\u524D\u306B\u691C\u51FA |\r\n| \u5F8C\u7F6E\u7B97\u8853 | \u30B5\u30D6\u30AF\u30A8\u30EA\u7D50\u679C\u3078\u306E\u7B97\u8853\u306F\u4E0D\u53EF\uFF08`(SELECT ...) * 2` \u306F\u4E0D\u53EF \u2192 `(SELECT COUNT(*) * 2 FROM ...)` \u3068\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\uFF09 |\r\n| \u30A8\u30E9\u30FC | \u8A55\u4FA1\u5931\u6557\uFF080 \u884C\u30FB\u8907\u6570\u884C\u30FB\u8907\u6570\u5217\u30FBAPI \u30A8\u30E9\u30FC\uFF09\u306F `ArgumentError` \u3067\u3001**`continueOnError` \u306B\u95A2\u308F\u3089\u305A\u30D0\u30C3\u30C1\u3092\u505C\u6B62**\uFF08fail-fast\u3002`ASSERT` \u5931\u6557\u306E\u505C\u6B62\uFF1D`assertion` \u3068\u306F\u533A\u5225\uFF09 |\r\n| EXPLAIN | \u30D0\u30C3\u30C1 EXPLAIN \u304C `SET @x = (SELECT ...)` \u306E\u30B5\u30D6\u30AF\u30A8\u30EA\u8A08\u753B\uFF08APP\uFF0F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u53C2\u7167\u30FB1 \u56DE\u8A55\u4FA1\uFF09\u3092\u8868\u793A |\r\n\r\n#### \u5916\u90E8\u30D1\u30E9\u30E1\u30FC\u30BF\u6CE8\u5165 `DECLARE @x = default`\r\n\r\n```sql\r\nDECLARE @since = '2026-01-01';\r\nSELECT * FROM APP100 WHERE \u767B\u9332\u65E5 >= @since;\r\n```\r\n\r\n- \u672A\u6CE8\u5165\u6642\u306F\u65E2\u5B9A\u5024\u3092\u5B9F\u884C\u6642\u306B1\u56DE\u8A55\u4FA1\u3002CLI \u306E `--var since=2026-07-01`\u3001MCP `variables: { \"since\": \"2026-07-01\" }` \u3067\u6587\u5B57\u5217\u5024\u3092\u4E0A\u66F8\u304D\u3067\u304D\u308B\u3002\u6CE8\u5165\u6642\u306F\u65E2\u5B9A\u5024\u5F0F\u3092\u8A55\u4FA1\u3057\u306A\u3044\u3002\r\n- \u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u3082 `DECLARE` \u6587\u306F\u5B9F\u884C\u3067\u304D\u308B\u304C\u6CE8\u5165 UI \u306F\u306A\u304F\u3001\u5E38\u306B\u65E2\u5B9A\u5024\u3092\u4F7F\u3046\u3002\r\n- \u30AD\u30FC\u306F `@` \u306A\u3057\u30FB\u5927\u6587\u5B57\u5C0F\u6587\u5B57\u3092\u533A\u5225\u3057\u306A\u3044\u3002\u672A\u5BA3\u8A00\u30AD\u30FC\u3001\u91CD\u8907\u3001\u4E0D\u6B63\u540D\u306F API \u547C\u3073\u51FA\u3057\u3084 DML \u3088\u308A\u524D\u306B\u30A8\u30E9\u30FC\u3002`SET` \u3067\u5B9A\u7FA9\u3057\u305F\u540D\u524D\u306F\u6CE8\u5165\u5BFE\u8C61\u306B\u306A\u3089\u306A\u3044\u3002\r\n- \u65E2\u5B9A\u5024\u306F\u30EA\u30C6\u30E9\u30EB\u30FB`NOW()` / `TODAY()`\u30FB\u6587\u5B57\u5217/\u6570\u5024\u95A2\u6570\u30FB\u6570\u5024\u7B97\u8853\u3002\u30B5\u30D6\u30AF\u30A8\u30EA\u3001\u5225\u5909\u6570\u3001`NULL`\u3001`LOGINUSER()` \u306F\u4E0D\u53EF\u3002\u63A1\u7528\u5024\u306F\u6587\u5B57\u5217\u3068\u3057\u3066\u675F\u7E1B\u3059\u308B\u3002\r\n- `DECLARE` \u3068\u4F7F\u7528\u6587\u3092\u542B\u30802\u6587\u4EE5\u4E0A\u306E\u30D0\u30C3\u30C1\u304C\u5FC5\u8981\u3002\u5024\u306F EXPLAIN\u3001\u7D50\u679C\u30E1\u30BF\u30C7\u30FC\u30BF\u306B\u8868\u793A\u3057\u306A\u3044\u3002CLI `--var` \u306F\u30D7\u30ED\u30BB\u30B9\u4E00\u89A7\u3084\u30B7\u30A7\u30EB\u5C65\u6B74\u306B\u6B8B\u308A\u5F97\u308B\u305F\u3081\u79D8\u5BC6\u60C5\u5831\u306B\u306F\u4F7F\u308F\u306A\u3044\u3002\r\n\r\n#### SELECT \u5B9A\u6570\u5217\u3068\u914D\u5217 IN\r\n\r\n```sql\r\nSET @batch = NOW();\r\nSET @ranks = ['A', 'B'];\r\nSELECT @batch AS \u30D0\u30C3\u30C1ID, \u9867\u5BA2No FROM APP100 WHERE \u9867\u5BA2\u30E9\u30F3\u30AF IN @ranks;\r\n```\r\n\r\n- `@x AS alias` \u306F\u6587\u5B57\u5217\u30FB\u6570\u5024\u3060\u3051\u3002\u914D\u5217\u306F SELECT \u5217\u306B\u7F6E\u3051\u306A\u3044\u3002`@x || field` \u306F\u5F93\u6765\u3069\u304A\u308A\u4E00\u822C\u30B9\u30AB\u30E9\u30FC\u5F0F\u3068\u3057\u3066\u6271\u3046\u3002\r\n- `IN @list` \u306F\u975E\u7A7A\u914D\u5217\u3092\u901A\u5E38\u306E literal IN \u3078\u5C55\u958B\u3059\u308B\u3002`IN (@x)` \u306F\u5F93\u6765\u3069\u304A\u308A\u30B9\u30AB\u30E9\u30FC 1 \u8981\u7D20\u3067\u3001\u914D\u5217\u5C55\u958B\u3067\u306F\u306A\u3044\u3002\r\n- \u7A7A\u914D\u5217\u306F `IN @empty`=\u507D\u3001`NOT IN @empty`=\u771F\u3068\u3057\u3066 AND/OR/NOT/\u62EC\u5F27\u3092\u7C21\u7D04\u3059\u308B\u3002SELECT \u306E\u6052\u507D WHERE \u306F\u30EC\u30B3\u30FC\u30C9 API \u3092\u547C\u3070\u305A\u7A7A\u5165\u529B\u3092\u5F8C\u6BB5\u3078\u6E21\u3059\u3002UPDATE/DELETE/\u975E ALL REORDER \u306E\u6700\u7D42 WHERE \u304C\u6052\u771F\u306B\u306A\u308B\u5834\u5408\u306F\u5168\u4EF6\u66F4\u65B0\u9632\u6B62\u306E\u305F\u3081\u5B9F\u884C\u524D\u30A8\u30E9\u30FC\u3001\u6052\u507D\u306F 0 \u4EF6 no-op\u3002\r\n\r\n**\u73FE\u6642\u70B9\u3067\u975E\u5BFE\u5FDC\uFF08\u4ECA\u5F8C\u306E\u30D5\u30A7\u30FC\u30BA\uFF09**: `NULL` \u306E\u4EE3\u5165\u30FB\u6570\u5024/\u6DF7\u5728\u914D\u5217\u30FB\u914D\u5217\u306E\u30B5\u30D6\u30AF\u30A8\u30EA\u4EE3\u5165\u30FB`IN (@list)` \u3067\u306E\u914D\u5217\u5C55\u958B\u30FB`SET` \u53F3\u8FBA\u3067\u306E\u5225\u5909\u6570\u53C2\u7167\u30FB\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u7D50\u679C\u3078\u306E\u7B97\u8853\u30FBSELECT \u5217\u306E\u4E00\u822C\u5F0F\u3068\u3057\u3066\u306E\u65B0\u3057\u3044\u5909\u6570\u5C55\u958B\u30FB\u95A2\u6570\u5F15\u6570\u3078\u306E `NOW()` \u76F4\u63A5\u6307\u5B9A\u30FB`LOGINUSER()`\u3002\r\n\r\n> **`APP@profile` \u3068\u306E\u4F75\u7528**: `SET @now = NOW(); SELECT * FROM APP100@dev WHERE \u4F5C\u6210\u65E5\u6642 = @now` \u306E\u3088\u3046\u306B\u3001`@profile`\uFF08\u30A2\u30D7\u30EA\u6307\u5B9A\uFF09\u3068 `@\u5909\u6570` \u306F\u540C\u5C45\u3067\u304D\u307E\u3059\uFF08CLI / MCP \u304C profile \u3060\u3051\u3092\u5148\u306B\u6B63\u898F\u5316\u3059\u308B\u305F\u3081\u6DF7\u540C\u3057\u307E\u305B\u3093\uFF09\u3002\r\n\r\n### \u6CE8\u610F\r\n\r\n- **\u30C8\u30E9\u30F3\u30B6\u30AF\u30B7\u30E7\u30F3\u306F\u3042\u308A\u307E\u305B\u3093**\u3002\u30D0\u30C3\u30C1\u3082\u975E\u30A2\u30C8\u30DF\u30C3\u30AF\u3067\u3059\uFF08DML \u30D0\u30C3\u30C1\u5BFE\u5FDC\u5F8C\u3082\u3001\u9014\u4E2D\u5931\u6557\u6642\u306B\u524D\u534A\u306E\u307F\u53CD\u6620\u3055\u308C\u305F\u72B6\u614B\u304C\u8D77\u3053\u308A\u5F97\u307E\u3059\uFF09\r\n- MCP \u3067\u306F `CREATE TEMP TABLE` \u306E\u5B9F\u4F53\u5316\u7D50\u679C\u306F\u8FD4\u5374\u3055\u308C\u307E\u305B\u3093\uFF08`tempTable` \u540D\u3068 `rowCount` \u306E\u307F\uFF09\u3002\u4E2D\u9593\u7D50\u679C\u3092\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u306B\u8F09\u305B\u306A\u3044\u305F\u3081\u306E\u8A2D\u8A08\u3067\u3059\r\n\r\n---", uri: "ksql://language-reference/25-batch-temp-tables" }, "26-assert": { heading: "26. ASSERT", text: '## 26. ASSERT\r\n\r\n> \u6761\u4EF6\u304C\u6210\u7ACB\u3057\u306A\u3051\u308C\u3070 `AssertError` \u3067\u5B9F\u884C\u3092\u6B62\u3081\u308B**\u5B9F\u884C\u6642\u30B2\u30FC\u30C8**\u3067\u3059\u3002DML \u524D\u306E\u4EF6\u6570\u30AC\u30FC\u30C9\u3084 CLI \u30D8\u30EB\u30B9\u30C1\u30A7\u30C3\u30AF\uFF08exit code \u76E3\u8996\uFF09\u306B\u4F7F\u3044\u307E\u3059\u3002\r\n\r\n```sql\r\nASSERT <\u5F0F> <\u6BD4\u8F03\u6F14\u7B97\u5B50> <\u5F0F>;\r\nASSERT <\u5F0F> BETWEEN <\u5F0F> AND <\u5F0F>;\r\n```\r\n\r\n- \u6BD4\u8F03\u6F14\u7B97\u5B50: `=` `<>` `!=` `<` `<=` `>` `>=` \u304A\u3088\u3073 `BETWEEN`\uFF08\u5883\u754C\u3092\u542B\u3080\uFF09\r\n- \u5F0F\u306B\u4F7F\u3048\u308B\u3082\u306E: **\u30EA\u30C6\u30E9\u30EB**\uFF08\u6570\u5024\u30FB\u6587\u5B57\u5217\uFF09\u3001**\u7B97\u8853\u5F0F**\uFF08\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u306E\u307F\uFF09\u3001**\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA**\uFF08`(SELECT ...)`\u3002APP\u30FB\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3068\u3082\u53C2\u7167\u53EF\uFF09\u3001**\u30D0\u30C3\u30C1\u5909\u6570**\uFF08`@\u540D\u524D`\u3002\u2192 [\xA725 \u30D0\u30C3\u30C1\u5909\u6570](#25-\u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB)\uFF09\r\n- \u6BD4\u8F03\u306E\u578B\u898F\u5247\u306F WHERE \u53E5\u3068\u540C\u4E00\uFF08`=` / `<>` \u306F\u6587\u5B57\u5217\u6BD4\u8F03\u3001\u5927\u5C0F\u6BD4\u8F03\u306F\u53CC\u65B9\u304C\u6570\u5024\u306A\u3089\u6570\u5024\u6BD4\u8F03\uFF09\r\n\r\n```sql\r\n-- \u5178\u578B\u4F8B1: UPDATE \u524D\u306E\u4EF6\u6570\u30AC\u30FC\u30C9\r\n-- \uFF08UPDATE \u306E\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3092\u53C2\u7167\u3067\u304D\u306A\u3044\u305F\u3081\u3001ASSERT \u3067\u76F4\u63A5\u4EF6\u6570\u3092\u691C\u8A3C\u3057\r\n-- UPDATE \u306B\u306F\u540C\u3058\u6761\u4EF6\u3092\u66F8\u304F\uFF09\r\nASSERT (SELECT COUNT(*) FROM APP100 WHERE \u58F2\u4E0A > 1000000) BETWEEN 1 AND 500;\r\n\r\nUPDATE APP100 SET \u72B6\u614B = \'\u5BFE\u8C61\' WHERE \u58F2\u4E0A > 1000000;\r\n```\r\n\r\n```sql\r\n-- \u5178\u578B\u4F8B2: \u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3092\u30B2\u30FC\u30C8 + SELECT-based DML \u306E\u30BD\u30FC\u30B9\u306B\u4F7F\u3046\r\n-- \uFF08INSERT/UPSERT ... SELECT \u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30BD\u30FC\u30B9\u5BFE\u5FDC\u306E\u305F\u3081\u3001\u691C\u8A3C\u3057\u305F #src \u3092\u305D\u306E\u307E\u307E\u66F8\u304D\u8FBC\u3081\u308B\uFF09\r\nCREATE TEMP TABLE #src AS\r\nSELECT \u9867\u5BA2\u540D, SUM(\u91D1\u984D) AS \u5408\u8A08 FROM APP200 GROUP BY \u9867\u5BA2\u540D;\r\n\r\nASSERT (SELECT COUNT(*) FROM #src) BETWEEN 1 AND 500;\r\n\r\nINSERT INTO APP300 (\u9867\u5BA2\u540D, \u5408\u8A08\u91D1\u984D) SELECT \u9867\u5BA2\u540D, \u5408\u8A08 FROM #src;\r\n```\r\n\r\n```bash\r\n# CLI \u30D8\u30EB\u30B9\u30C1\u30A7\u30C3\u30AF\uFF08\u4E0D\u6210\u7ACB\u306A\u3089 exit code 1\uFF09\r\nksql -e "ASSERT (SELECT COUNT(*) FROM APP1 WHERE \u7570\u5E38\u30D5\u30E9\u30B0 = \'1\') = 0"\r\n```\r\n\r\n### \u52D5\u4F5C\r\n\r\n- **read-only \u6271\u3044**\u3067\u3059\uFF08kintone \u306B\u66F8\u304D\u8FBC\u307E\u306A\u3044\uFF09\u3002read-only \u30D0\u30C3\u30C1\u30FBDML \u30D0\u30C3\u30C1\u306E\u3069\u3061\u3089\u306B\u3082\u66F8\u3051\u307E\u3059\u3002\u5358\u6587\u3067\u3082\u5B9F\u884C\u3067\u304D\u307E\u3059\r\n- \u4E0D\u6210\u7ACB\u306E\u5834\u5408\u306F `AssertError: assertion failed: <\u6761\u4EF6> (actual: <\u5B9F\u6E2C\u5024>).` \u3067\u305D\u306E\u6587\u304C\u30A8\u30E9\u30FC\u306B\u306A\u308A\u3001**\u30D0\u30C3\u30C1\u306F\u5E38\u306B\u505C\u6B62**\u3057\u307E\u3059\uFF08`continueOnError` \u6307\u5B9A\u3082\u7121\u8996\u3002\u4EE5\u964D\u306E\u6587\u306F `skipped` / `skippedReason: "assertion"`\uFF09\r\n- \u30D0\u30C3\u30C1\u6210\u529F\u6642\u306E ASSERT \u306F\u7D50\u679C\u3092\u6301\u305F\u306A\u3044\u6587\u3068\u3057\u3066\u6271\u308F\u308C\u307E\u3059\uFF08`statements[]` \u306F `status: "success"` \u306E\u307F\uFF09\r\n- \u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306F**\u5FC5\u305A 1\u884C1\u5217**\u3092\u8981\u6C42\u3057\u307E\u3059\u30020\u884C\u30FB\u8907\u6570\u884C\u306F\u5B9F\u884C\u6642 `AssertError`\uFF080\u884C\u3092 NULL \u6271\u3044\u306B\u3057\u307E\u305B\u3093\uFF09\u3002\u8907\u6570\u5217\u306F select list \u304C\u660E\u793A\u7684\u306A\u3089\u30D1\u30FC\u30B9\u6642\u306B\u62D2\u5426\u3001`SELECT *` \u7B49\u306F\u5B9F\u884C\u6642\u306B\u691C\u8A3C\u3057\u307E\u3059\r\n- **GROUP BY \u306A\u3057\u306E\u96C6\u8A08\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u5BFE\u8C61 0 \u4EF6\u3067\u3082 1 \u884C\uFF08COUNT \u306F `0`\uFF09\u3092\u8FD4\u3059**\uFF08\xA78\u300C0 \u4EF6\u6642\u306E\u6319\u52D5\u300D\uFF09\u305F\u3081\u3001\u4E0A\u306E CLI \u4F8B\u306E\u3088\u3046\u306A `ASSERT (SELECT COUNT(*) ... WHERE \u7570\u5E38\u6761\u4EF6) = 0` \u306E\u5065\u5168\u6027\u30C1\u30A7\u30C3\u30AF\u304C\u8A72\u5F53 0 \u4EF6\uFF08\u5065\u5168\u6642\uFF09\u306B\u6210\u7ACB\u3057\u307E\u3059\u30020 \u884C\u30A8\u30E9\u30FC\u304C\u8D77\u304D\u308B\u306E\u306F\u3001\u975E\u96C6\u8A08\u30D7\u30ED\u30FC\u30D6\u306E\u7A7A\u632F\u308A\uFF08`SELECT \u30D5\u30A3\u30FC\u30EB\u30C9 FROM ... WHERE ...` \u304C 0 \u4EF6\uFF09\u3084 GROUP BY \u4ED8\u304D\u96C6\u8A08\u304C 0 \u884C\u306B\u306A\u308B\u5834\u5408\u3067\u3059\r\n\r\n### \u5236\u9650\uFF08\u521D\u671F\u7248\uFF09\r\n\r\n| \u9805\u76EE | \u5185\u5BB9 |\r\n|---|---|\r\n| `AND` / `OR` \u306E\u8907\u5408\u6761\u4EF6 | \u975E\u5BFE\u5FDC\uFF08\u8907\u6570\u306E `ASSERT` \u6587\u306B\u5206\u3051\u3066\u66F8\u304F\uFF09 |\r\n| \u88F8\u306E\u5024\u306E\u307F\uFF08`ASSERT 1`\uFF09 | \u975E\u5BFE\u5FDC\uFF08\u6BD4\u8F03\u6F14\u7B97\u5B50\u307E\u305F\u306F BETWEEN \u304C\u5FC5\u9808\uFF09 |\r\n| \u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167 | \u975E\u5BFE\u5FDC\uFF08FROM \u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u304C\u306A\u3044\u305F\u3081\u3002\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u306F\u4F7F\u7528\u53EF\uFF09 |\r\n| \u95A2\u6570\u547C\u3073\u51FA\u3057 | \u5F0F\u306E\u76F4\u4E0B\u3067\u306F\u975E\u5BFE\u5FDC\uFF08\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3059\u308B\uFF09 |\r\n| \u30B5\u30D6\u30AF\u30A8\u30EA\u76F4\u5F8C\u306E\u7B97\u8853 | \u975E\u5BFE\u5FDC\uFF08`(SELECT ...) * 2` \u306F\u4E0D\u53EF\u3002\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3059\u308B\uFF09 |\r\n\r\n> **\u6CE8\u610F\uFF08\u65E2\u5B58\u5236\u9650\u3068\u306E\u7D44\u307F\u5408\u308F\u305B\uFF09**: `UPDATE` / `DELETE` \u306E\u30B5\u30D6\u30AF\u30A8\u30EA\u3067\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\uFF08`ArgumentError: temp table references in UPDATE are not supported yet.` \u2014 \xA725\uFF09\u3002`ASSERT` \u81EA\u4F53\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3092\u53C2\u7167\u3067\u304D\u308B\u305F\u3081\u3001\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3067\u4EF6\u6570\u3092\u691C\u8A3C\u3057\u3064\u3064\u5F8C\u7D9A\u306E `UPDATE` / `DELETE` \u306B\u306F\u540C\u3058 WHERE \u6761\u4EF6\u3092\u76F4\u63A5\u66F8\u304F\u304B\u3001\u5F8C\u7D9A\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30BD\u30FC\u30B9\u5BFE\u5FDC\u306E `INSERT` / `UPSERT ... SELECT` \u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n---', uri: "ksql://language-reference/26-assert" } } }, recipes: { title: "kSQL \u30D0\u30C3\u30C1\u8A2D\u8A08\u30EC\u30B7\u30D4\u96C6", index: "# kSQL \u30D0\u30C3\u30C1\u8A2D\u8A08\u30EC\u30B7\u30D4\u96C6 index\n\nSafe, rerunnable batch design recipes for CLI, MCP, and the plugin.\n\nSource: `docs/ksql_batch_recipes.md`\n\n## \u8A2D\u8A08\u539F\u5247\uFF08\u30EA\u30E9\u30F3\u53EF\u80FD\u30D0\u30C3\u30C1\uFF09\r\n\r\nkSQL \u30D0\u30C3\u30C1\u306F**\u30C8\u30E9\u30F3\u30B6\u30AF\u30B7\u30E7\u30F3\u3092\u6301\u305F\u305A\u975E\u30A2\u30C8\u30DF\u30C3\u30AF**\u3067\u3059\u3002\u3044\u3064\u5931\u6557\u3057\u3066\u3082**\u5148\u982D\u304B\u3089\u306E\u30EA\u30E9\u30F3\u3060\u3051\u3067\u6B63\u3057\u304F\u56DE\u5FA9\u3067\u304D\u308B**\u8A2D\u8A08\u306B\u3057\u307E\u3059\u3002\r\n\r\n1. **\u30B9\u30C6\u30FC\u30BF\u30B9\u99C6\u52D5**: \u5BFE\u8C61\u3092\u300C\u672A\u51E6\u7406 \u2192 \u51E6\u7406\u4E2D \u2192 \u51E6\u7406\u6E08\u300D\u3067\u7BA1\u7406\u3059\u308B\u3002\r\n2. **\u4E2D\u65AD\u5FA9\u65E7\u3092\u5148\u982D\u306B**: \u524D\u56DE\u306E\u4E2D\u65AD\u3067\u300C\u51E6\u7406\u4E2D\u300D\u306B\u6B8B\u3063\u305F\u5BFE\u8C61\u3092\u3001\u30EA\u30E9\u30F3\u5192\u982D\u3067\u300C\u672A\u51E6\u7406\u300D\u306B\u623B\u3059\uFF08R1 \u306E 0\uFF09\u3002\u3053\u308C\u304C\u7121\u3044\u3068 claim-first \u306F\u300C\u51E6\u7406\u4E2D\u300D\u3092\u62FE\u3048\u305A\u56DE\u5FA9\u3067\u304D\u306A\u3044\u3002\r\n3. **\u78BA\u4FDD \u2192 \u672C\u51E6\u7406 \u2192 \u5B8C\u4E86 \u306E\u9806\uFF08fail-fast\uFF09**: \u5BFE\u8C61\u3092\u81EA\u5206\u306E\u30D0\u30C3\u30C1 ID \u3067\u300C\u51E6\u7406\u4E2D\u300D\u306B\u78BA\u4FDD \u2192 \u30DE\u30B9\u30BF\u66F8\u304D\u8FBC\u307F \u2192 \u300C\u51E6\u7406\u6E08\u300D\u3002\u9014\u4E2D\u5931\u6557\u306F fail-fast \u3067\u5F8C\u6BB5\u306B\u9032\u307E\u305A\u3001\u6B21\u56DE\u30EA\u30E9\u30F3\u3067 0\uFF09\u304C\u56DE\u53CE\u3057\u3066\u518D\u51E6\u7406\u3059\u308B\u3002\u203B \u90E8\u5206\u6210\u529F\u3092\u691C\u51FA\u3057\u3066\u5DEE\u5206\u3060\u3051\u66F4\u65B0\u3059\u308B\u4ED5\u7D44\u307F\u3067\u306F\u306A\u3044\u3002\r\n4. **\u4EF6\u6570\u30B2\u30FC\u30C8**: \u78BA\u4FDD\u5BFE\u8C61\u306E\u4E0A\u9650\u306F\u78BA\u4FDD\u306E\u524D\u306B\u3001\u5B9F\u969B\u306B\u78BA\u4FDD\u3067\u304D\u305F\u4EF6\u6570\u306F\u78BA\u4FDD\u306E\u5F8C\u306B ASSERT \u3059\u308B\u3002**\u5DEE\u5206 0 \u4EF6\u3092\u6B63\u5E38\u3068\u3059\u308B\u304B\u7570\u5E38\u3068\u3059\u308B\u304B\u306F\u904B\u7528\u3067\u9078\u3076**\uFF08\u4E0B\u8A18\uFF09\u3002\r\n5. **\u51AA\u7B49**: `UPSERT`\uFF08\u30AD\u30FC\u4E00\u81F4\u3067\u66F4\u65B0\u30FB\u306A\u3051\u308C\u3070\u633F\u5165\uFF09\u3002\u305F\u3060\u3057**\u30AD\u30FC\u304C\u30BD\u30FC\u30B9\u30FB\u30DE\u30B9\u30BF\u53CC\u65B9\u3067\u4E00\u610F**\u304C\u524D\u63D0\u3002\r\n6. **\u6642\u523B\u30FB\u30D0\u30C3\u30C1 ID \u306E\u56FA\u5B9A**: `SET @now = NOW()` \u3092 1 \u56DE\u3060\u3051\u8A55\u4FA1\u3057\u3001\u78BA\u4FDD\u30FB\u5B8C\u4E86\u30FB\u7A81\u5408\u3067\u4F7F\u3044\u56DE\u3059\uFF081a \u3067\u306F `SET @b = @a` \u4E0D\u53EF\uFF09\u3002\r\n\r\n---\n\n## Sections\n\n- [R1. \u5DEE\u5206\u66F4\u65B0\u30D0\u30C3\u30C1\uFF08\u5FA9\u65E7 \u2192 \u78BA\u4FDD \u2192 \u51E6\u7406 \u2192 \u5B8C\u4E86\uFF09](ksql://recipes/r1)\n- [R2. \u4E8B\u524D\u30B2\u30FC\u30C8\uFF08\u4EF6\u6570\u30C1\u30A7\u30C3\u30AF\u30FBinserts/updates \u5185\u8A33\uFF09](ksql://recipes/r2)\n- [R3. \u66F4\u65B0\u524D\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\uFF08`#before`\uFF09](ksql://recipes/r3)\n- [R4. \u30D0\u30C3\u30C1\u5909\u6570\u306E\u6D3B\u7528\uFF08v2.1.0\uFF09](ksql://recipes/r4)\n- [R5. \u30EA\u30C6\u30E9\u30EB\u5024\u30EA\u30B9\u30C8\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u5316\u3057\u3066\u4E00\u62EC\u51E6\u7406](ksql://recipes/r5)\n- [R6. \u4E0D\u826F\u30C7\u30FC\u30BF\u3092\u9694\u96E2\u3057\u3066\u6B8B\u308A\u3092\u6D41\u3059\uFF08`ON ERROR SKIP`\u30FBv2.13.0\uFF09](ksql://recipes/r6)\n- [R7. kintone \u306E REST API \u3068\u540C\u3058\u4E26\u3073\u3067\u5927\u91CF\u53D6\u5F97\u3059\u308B\uFF08`KORDER BY`\u30FBv3.0.0 / v3.1.0\uFF09](ksql://recipes/r7)\n- [R8. Shift_JIS \u3067\u51FA\u529B\u3067\u304D\u306A\u3044\u6F22\u5B57\u3092\u5909\u63DB\u3059\u308B\uFF08v3.2.0\uFF09](ksql://recipes/r8)\n- [R9. \u30C7\u30FC\u30BF\u54C1\u8CEA\u30C1\u30A7\u30C3\u30AF \u2014 \u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u30FB\u6587\u5B57\u6570\u4E88\u7B97\uFF08v3.2.0\uFF09](ksql://recipes/r9)\n- [R10. \u8868\u8A18\u306E\u6B63\u898F\u5316\u3092\u66F8\u304D\u623B\u3059\uFF08`UPDATE SET` \u306E\u6587\u5B57\u5217\u95A2\u6570\u30FBv3.2.0\uFF09](ksql://recipes/r10)\n- [R11. \u30D5\u30A1\u30A4\u30EB\u304B\u3089\u30A2\u30D7\u30EA\u3078\u53D6\u8FBC\u3080\uFF08`IMPORT`\u30FBv3.6.0\uFF09](ksql://recipes/r11)\n- [R12. cli-kintone \u3068 round-trip \u3059\u308B\uFF08`BY NAME`\u30FB\u30EC\u30B3\u30FC\u30C9\u756A\u53F7 UPDATE\u30FB\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u30FBv3.6.0\uFF09](ksql://recipes/r12)\n\nIndex URI: ksql://recipes", sections: { r1: { heading: "R1. \u5DEE\u5206\u66F4\u65B0\u30D0\u30C3\u30C1\uFF08\u5FA9\u65E7 \u2192 \u78BA\u4FDD \u2192 \u51E6\u7406 \u2192 \u5B8C\u4E86\uFF09", text: "## R1. \u5DEE\u5206\u66F4\u65B0\u30D0\u30C3\u30C1\uFF08\u5FA9\u65E7 \u2192 \u78BA\u4FDD \u2192 \u51E6\u7406 \u2192 \u5B8C\u4E86\uFF09\r\n\r\n\u89AA DML \u306E WHERE \u306B\u306F `IN (SELECT \u2026)` \u3092\u66F8\u3051\u306A\u3044\u305F\u3081\u3001**\u5BFE\u8C61\u3092\u30D0\u30C3\u30C1 ID \u3067\u78BA\u4FDD\u3057\u3066\u304B\u3089\u76F4\u63A5\u6761\u4EF6\u3067\u5B8C\u4E86**\u3055\u305B\u3001**\u4E2D\u65AD\u3067\u300C\u51E6\u7406\u4E2D\u300D\u306B\u6B8B\u3063\u305F\u5BFE\u8C61\u306F\u5192\u982D\u3067\u56DE\u53CE**\u3057\u307E\u3059\u3002\r\n\r\n```sql\r\nSET @now = NOW(); -- 1 \u56DE\u3060\u3051\u8A55\u4FA1\u3057\u3001\u78BA\u4FDD\u30FB\u5B8C\u4E86\u3067\u4F7F\u3044\u56DE\u3059\r\n\r\n-- 0) \u5FA9\u65E7: \u524D\u56DE\u306E\u4E2D\u65AD\u3067\u300C\u51E6\u7406\u4E2D\u300D\u306B\u6B8B\u3063\u305F\u5BFE\u8C61\u3092\u300C\u672A\u51E6\u7406\u300D\u306B\u623B\u3059\uFF08\u30EA\u30E9\u30F3\u56DE\u5FA9\u306E\u8981\uFF09\r\n-- \u78BA\u4FDD\u65E5\u6642\u306B\u7336\u4E88\u3092\u8A2D\u3051\u3001\u5F53\u65E5\u5B9F\u884C\u4E2D\u306E\u4ED6\u30D7\u30ED\u30BB\u30B9\u304C\u78BA\u4FDD\u3057\u305F\u884C\u3092\u6A2A\u53D6\u308A\u3057\u306A\u3044\r\n-- \uFF08WHERE \u306E \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 \u306F\u9078\u629E\u7CFB\u30D5\u30A3\u30FC\u30EB\u30C9\u60F3\u5B9A\u3067 IN\u3002SET \u306F = \u306E\u307E\u307E\uFF09\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u672A\u51E6\u7406'\r\nWHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u51E6\u7406\u4E2D') AND \u78BA\u4FDD\u65E5\u6642 < TODAY();\r\n\r\n-- 1) \u4EF6\u6570\u30B2\u30FC\u30C8\uFF08\u78BA\u4FDD\u5BFE\u8C61\u306E\u4E0A\u9650\u30020 \u4EF6\u3092\u6B63\u5E38\u306B\u3059\u308B\u306A\u3089 BETWEEN 0 \u2026\u3001\u7570\u5E38\u691C\u77E5\u3057\u305F\u3044\u306A\u3089 BETWEEN 1 \u2026\uFF09\r\nASSERT (SELECT COUNT(*) FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406')) BETWEEN 0 AND 10000;\r\n\r\n-- 2) \u78BA\u4FDD: \u672A\u51E6\u7406\u3092\u81EA\u5206\u306E\u30D0\u30C3\u30C1 ID \u3067\u300C\u51E6\u7406\u4E2D\u300D\u306B\uFF08\u76F4\u63A5\u6761\u4EF6\u30FB\u78BA\u4FDD\u65E5\u6642\u3082\u4ED8\u4E0E\uFF09\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u51E6\u7406\u4E2D', \u30D0\u30C3\u30C1ID = @now, \u78BA\u4FDD\u65E5\u6642 = @now\r\nWHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n\r\n-- 3) \u78BA\u4FDD\u3057\u305F\u5206\u3092\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\uFF08\u30D0\u30C3\u30C1 ID\uFF0B\u51E6\u7406\u4E2D\u306E\u76F4\u63A5\u6761\u4EF6\uFF09\r\nCREATE TEMP TABLE #tgt AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP100 WHERE \u30D0\u30C3\u30C1ID = @now AND \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u51E6\u7406\u4E2D');\r\n\r\n-- 4) \u78BA\u4FDD\u5F8C\u30B2\u30FC\u30C8\uFF08\u5B9F\u969B\u306B\u78BA\u4FDD\u3067\u304D\u305F\u4EF6\u6570\u306E\u4E0A\u9650\uFF09\uFF0B\u30AD\u30FC\u4E00\u610F\u30B2\u30FC\u30C8\uFF08\u51AA\u7B49\u6027\u306E\u524D\u63D0\uFF09\r\nASSERT (SELECT COUNT(*) FROM #tgt) <= 10000;\r\nASSERT (SELECT COUNT(*) FROM #tgt) = (SELECT COUNT(DISTINCT \u9867\u5BA2\u30B3\u30FC\u30C9) FROM #tgt);\r\n\r\n-- 5) \u672C\u51E6\u7406: \u30DE\u30B9\u30BF\u3078 UPSERT\uFF08UPSERT \u2026 SELECT \u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u53C2\u7167\u53EF\uFF09\r\nUPSERT INTO APP200 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM #tgt\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9);\r\n\r\n-- 6) \u5B8C\u4E86: \u78BA\u4FDD\u3057\u305F\u5206\u3092\u300C\u51E6\u7406\u6E08\u300D\u306B\uFF08\u76F4\u63A5\u6761\u4EF6\uFF09\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u51E6\u7406\u6E08', \u51E6\u7406\u65E5\u6642 = @now\r\nWHERE \u30D0\u30C3\u30C1ID = @now AND \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u51E6\u7406\u4E2D');\r\n```\r\n\r\n**\u306A\u305C\u3053\u306E\u5F62\u304B**\r\n- **0) \u306E\u5FA9\u65E7\u304C\u300C\u5148\u982D\u304B\u3089\u306E\u30EA\u30E9\u30F3\u3060\u3051\u3067\u56DE\u5FA9\u300D\u3092\u6210\u7ACB\u3055\u305B\u308B**: 5) \u3084 6) \u3067\u5931\u6557\u3059\u308B\u3068\u5BFE\u8C61\u306F\u300C\u51E6\u7406\u4E2D\u300D\u3067\u6B8B\u308B\u3002\u5FA9\u65E7\u304C\u7121\u3044\u3068\u3001\u6B21\u56DE\u30EA\u30E9\u30F3\u306F\u65B0\u3057\u3044 `@now` \u3067\u300C\u672A\u51E6\u7406\u300D\u3060\u3051\u3092\u898B\u308B\u305F\u3081\u53D6\u308A\u6B8B\u3059\u30020) \u304C\u7336\u4E88\uFF08`\u78BA\u4FDD\u65E5\u6642 < TODAY()`\uFF09\u4ED8\u304D\u3067\u56DE\u53CE\u3059\u308B\u306E\u3067\u3001\u7FCC\u5B9F\u884C\u3067\u518D\u51E6\u7406\u3055\u308C\u308B\u3002\r\n - **\u7336\u4E88\u306E\u610F\u5473**: `\u78BA\u4FDD\u65E5\u6642 < TODAY()` \u306F\u300C\u5F53\u65E5\u5B9F\u884C\u4E2D\u306E\u5225\u30D7\u30ED\u30BB\u30B9\u304C\u78BA\u4FDD\u3057\u305F\u884C\u3092\u6A2A\u53D6\u308A\u3057\u306A\u3044\u300D\u305F\u3081\u306E\u6700\u5C0F\u306E\u7336\u4E88\u3067\u3059\u3002\u5F53\u65E5\u4E2D\u306E\u518D\u5B9F\u884C\u3067\u56DE\u5FA9\u3057\u305F\u3044\u5834\u5408\u306F\u3001\u7336\u4E88\uFF08\u30EA\u30FC\u30B9\u671F\u9650\uFF09\u3092\u30B8\u30E7\u30D6\u5236\u5FA1\u5074\u3067\u6301\u3064\u304B\u3001\u624B\u52D5\u3067\u300C\u51E6\u7406\u4E2D \u2192 \u672A\u51E6\u7406\u300D\u306B\u623B\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n- **\u78BA\u4FDD\uFF082\uFF09\u30FB\u5B8C\u4E86\uFF086\uFF09\u306F\u76F4\u63A5\u6761\u4EF6**\u3067\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3092\u53C2\u7167\u3057\u306A\u3044 \u2192 \u5B9F\u884C\u62D2\u5426\u3092\u907F\u3051\u308B\u3002\u672C\u51E6\u7406\uFF085\uFF09\u3060\u3051\u304C `UPSERT \u2026 SELECT FROM #tgt`\uFF08\u8A31\u53EF\uFF09\u3002\r\n- **\u591A\u91CD\u8D77\u52D5\u306E\u7DE9\u548C**: 2) \u3067\u300C\u51E6\u7406\u4E2D\u300D\u306B\u78BA\u4FDD\u3059\u308B\u305F\u3081\u3001\u5225\u5B9F\u884C\u304C\u540C\u3058\u300C\u672A\u51E6\u7406\u300D\u3092\u4E8C\u91CD\u306B\u62FE\u3044\u306B\u304F\u3044\u3002\u305F\u3060\u3057 kintone \u306B\u30EC\u30B3\u30FC\u30C9\u30ED\u30C3\u30AF\u306F\u7121\u304F\u3001**\u78BA\u4FDD UPDATE \u81EA\u4F53\u306F\u7AF6\u5408\u3057\u5F97\u308B\uFF1D\u5B8C\u5168\u306A\u6392\u4ED6\u3067\u306F\u306A\u3044**\u3002\u5225\u5B9F\u884C\u304C\u5148\u306B\u5168\u4EF6\u78BA\u4FDD\u3059\u308B\u3068\u3001\u3053\u306E\u30D0\u30C3\u30C1\u306E\u78BA\u4FDD\u306F 0 \u4EF6\u306B\u306A\u308A\u3001\u4EE5\u964D\u306F\u300C\u3084\u308B\u3053\u3068\u306A\u3057\u300D\u3067\u6B63\u5E38\u7D42\u4E86\u3059\u308B\uFF080 \u4EF6\u3092\u8A31\u5BB9\u3059\u308B\u5834\u5408\uFF09\u3002**\u53B3\u5BC6\u306A\u6392\u4ED6\u306F\u30B8\u30E7\u30D6\u5236\u5FA1\u5074**\uFF08cron \u306E\u591A\u91CD\u8D77\u52D5\u9632\u6B62\u30FB\u30ED\u30C3\u30AF\uFF09\u3067\u4FDD\u8A3C\u3002\r\n - `NOW()` \u306F**\u53B3\u5BC6\u306B\u4E00\u610F\u306A ID \u3067\u306F\u306A\u3044**\uFF08\u540C\u4E00\u30DF\u30EA\u79D2\u8D77\u52D5\u3067\u540C\u5024\uFF09\u3002\u78BA\u5B9F\u306A\u4E00\u610F\u6027\u304C\u8981\u308B\u5834\u5408\u306F\u547C\u3073\u51FA\u3057\u5074\u3067\u63A1\u756A\u3057\u305F ID \u3092 `DECLARE @batchId = ...` \uFF0B CLI `--var`\uFF0FMCP `variables` \u3067\u6CE8\u5165\u3059\u308B\uFF08R4 \u53C2\u7167\uFF09\u3002\r\n\r\n**\u5DEE\u5206 0 \u4EF6\uFF08\uFF1D\u7A7A\u65E5\uFF09\u306E\u6271\u3044**\r\n- \u65E5\u6B21 cron \u3067\u306F\u300C\u4ECA\u65E5\u306F\u5DEE\u5206\u306A\u3057\u300D\u306F\u6B63\u5E38\u7CFB\u3067\u3059\u30021) \u3092 `BETWEEN 0 AND 10000` \u306B\u3059\u308B\u3068 0 \u4EF6\u3067\u6B63\u5E38\u7D42\u4E86\u3057\u307E\u3059\u3002`BETWEEN 1 \u2026` \u306B\u3059\u308B\u3068 0 \u4EF6\u3067 ASSERT \u5931\u6557\uFF1D\u30A2\u30E9\u30FC\u30C8\u306B\u306A\u308B\u306E\u3067\u3001**\u5DEE\u5206\u30BC\u30ED\u3092\u7570\u5E38\u3068\u3057\u3066\u691C\u77E5\u3057\u305F\u3044\u5834\u5408\u306E\u307F**\u305D\u3061\u3089\u306B\u3057\u307E\u3059\u3002\r\n- 0 \u4EF6\u306E\u3068\u304D `#tgt` \u306F 0 \u884C\u3067\u3001`UPSERT \u2026 SELECT FROM #tgt` \u306F **`inserted=0 / updated=0` \u306E no-op** \u3068\u3057\u3066\u305D\u306E\u307E\u307E\u5B8C\u8D70\u3057\u307E\u3059\uFF08\u66F8\u304D\u8FBC\u307F API \u3082\u547C\u3070\u308C\u307E\u305B\u3093\uFF09\u3002**v2.1.1 \u4EE5\u964D**\u306E\u6319\u52D5\u3067\u3059\uFF08v2.1.0 \u4EE5\u524D\u306F\u7A7A\u30BD\u30FC\u30B9\u306E `UPSERT \u2026 SELECT` \u304C\u300CSELECT \u306E\u5217\u6570\uFF080\uFF09\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093\u300D\u3067\u505C\u6B62\u3057\u305F\u305F\u3081\u3001`BETWEEN 1` \u3067 0 \u4EF6\u3092\u66F8\u304D\u8FBC\u307F\u524D\u306B\u6B62\u3081\u308B\u30FB\u547C\u3073\u51FA\u3057\u5074\u3067\u4EF6\u6570\u3092\u5148\u306B\u78BA\u8A8D\u3057\u3066\u30B9\u30AD\u30C3\u30D7\u3001\u3068\u3044\u3063\u305F\u56DE\u907F\u7B56\u304C\u5FC5\u8981\u3067\u3057\u305F\u3002v2.1.1 \u3067\u3053\u308C\u3089\u306F\u4E0D\u8981\u3067\u3059\uFF09\u3002\u5B9F\u6A5F\u3067\u3082\u5DEE\u5206 0 \u4EF6\u30EA\u30E9\u30F3\u304C\u5168\u6587 0 \u4EF6\u3067\u5B8C\u8D70\u3059\u308B\u3053\u3068\u3092\u78BA\u8A8D\u6E08\u307F\u3067\u3059\u3002\r\n- **v2.11.0 \u4EE5\u964D**\u306F\u3001\u540C\u3058\u7A7A\u65E5\u306B `SELECT * FROM #tgt` \u3092 `INSERT` / `UPSERT` \u30BD\u30FC\u30B9\u306B\u3057\u3066\u3082\u3001\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u5B9F\u4F53\u5316\u6642\u306E\u5217\u30B9\u30AD\u30FC\u30DE\u304C\u4FDD\u6301\u3055\u308C\u308B\u305F\u3081\u540C\u3058 no-op \u3067\u5B8C\u8D70\u3057\u307E\u3059\u3002\u5217\u3092\u660E\u793A\u3059\u308B\u73FE\u884C R1 \u30EC\u30B7\u30D4\u306E\u6319\u52D5\u306F\u4E0D\u5909\u3067\u3059\u3002\r\n\r\n**\u51AA\u7B49\u6027\u30FB\u30EA\u30E9\u30F3\u306E\u6CE8\u610F**\r\n- **\u30AD\u30FC\u4E00\u610F\u304C\u524D\u63D0**: `#tgt`\u30FB`APP200` \u53CC\u65B9\u3067 `\u9867\u5BA2\u30B3\u30FC\u30C9` \u304C\u4E00\u610F\u306E\u3068\u304D\u3060\u3051 UPSERT \u304C\u51AA\u7B49\u3002\u30BD\u30FC\u30B9\u5185\u30AD\u30FC\u91CD\u8907\u306F\u521D\u56DE\u306B\u91CD\u8907\u767B\u9332\u3055\u308C\uFF08\u6B21\u56DE\u4EE5\u964D\u306F\u66F4\u65B0\u306B\u56DE\u308B\u306E\u3067\u7121\u9650\u306B\u306F\u5897\u3048\u306A\u3044\u304C\u3001\u3067\u304D\u305F\u91CD\u8907\u306F\u6B8B\u308A\u6B63\u3057\u3044\u56DE\u5FA9\u3082\u4FDD\u8A3C\u3067\u304D\u306A\u3044\uFF09\u30014) \u3067\u6B62\u3081\u308B\u3002\u30DE\u30B9\u30BF\u5074\u91CD\u8907\u6642\u306F\u66F4\u65B0\u304C\u6700\u5927 `$id` \u306E 1 \u4EF6\u306E\u307F\u3002\r\n- **\u4E8B\u5F8C\u7A81\u5408\u306F\u4EFB\u610F\uFF08\u691C\u51FA\u529B\u306F\u4E0B\u304C\u3063\u305F\uFF09**: claim-first \u3067\u306F `#tgt` \u3092\u300C\u78BA\u4FDD\u5F8C\u306E `\u30D0\u30C3\u30C1ID=@now`\u300D\u304B\u3089\u4F5C\u308A 6) \u3082\u540C\u6761\u4EF6\u3067\u66F4\u65B0\u3059\u308B\u305F\u3081\u3001`\u51E6\u7406\u6E08\u4EF6\u6570 = #tgt\u4EF6\u6570` \u306F\u307B\u307C\u81EA\u660E\uFF08\u304B\u3064\u5931\u6557\u3059\u308C\u3070 fail-fast \u3067\u5230\u9054\u3057\u306A\u3044\uFF09\u3002\u4ED8\u3051\u308B\u306A\u3089\u6B21\u3092 6) \u306E\u5F8C\u306B\u3002\r\n ```sql\r\n ASSERT (SELECT COUNT(*) FROM APP100 WHERE \u30D0\u30C3\u30C1ID = @now AND \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u51E6\u7406\u6E08'))\r\n = (SELECT COUNT(*) FROM #tgt);\r\n ```\r\n\r\n---", uri: "ksql://recipes/r1" }, r2: { heading: "R2. \u4E8B\u524D\u30B2\u30FC\u30C8\uFF08\u4EF6\u6570\u30C1\u30A7\u30C3\u30AF\u30FBinserts/updates \u5185\u8A33\uFF09", text: "## R2. \u4E8B\u524D\u30B2\u30FC\u30C8\uFF08\u4EF6\u6570\u30C1\u30A7\u30C3\u30AF\u30FBinserts/updates \u5185\u8A33\uFF09\r\n\r\n\u66F8\u304D\u8FBC\u307F\u524D\u306B\u300C\u4F55\u4EF6\u3092\u65B0\u898F\u4F5C\u6210\u3057\u3001\u4F55\u4EF6\u3092\u66F4\u65B0\u3059\u308B\u304B\u300D\u3092\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u3067\u78BA\u8A8D\u3057\u307E\u3059\uFF08\u66F8\u304D\u8FBC\u307F\u306A\u3057\uFF09\u3002\r\n\r\n```sql\r\nCREATE TEMP TABLE #tgt AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n\r\n-- \u60F3\u5B9A\u5916\u4EF6\u6570\u306A\u3089\u505C\u6B62\uFF08\u30B2\u30FC\u30C8\u306F\u5148\u982D\u306B\uFF09\r\nASSERT (SELECT COUNT(*) FROM #tgt) BETWEEN 1 AND 10000;\r\n\r\n-- inserts\uFF08\u30DE\u30B9\u30BF\u672A\u5B58\u5728\uFF09\u3068 updates\uFF08\u30DE\u30B9\u30BF\u5B58\u5728\uFF09\u3092 1 \u7D50\u679C\u30BB\u30C3\u30C8\u3067\r\n-- COUNT(\u30D5\u30A3\u30FC\u30EB\u30C9) \u306F\u7A7A\u6587\u5B57\u30FBNULL\uFF08\uFF1DLEFT JOIN \u672A\u30DE\u30C3\u30C1\uFF09\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3066\u6570\u3048\u308B\uFF08\xA78\uFF09\r\nSELECT\r\n COUNT(*) AS \u5BFE\u8C61\u4EF6\u6570,\r\n COUNT(m.\u9867\u5BA2\u30B3\u30FC\u30C9) AS updates,\r\n COUNT(*) - COUNT(m.\u9867\u5BA2\u30B3\u30FC\u30C9) AS inserts\r\nFROM #tgt t LEFT JOIN APP200 m ON t.\u9867\u5BA2\u30B3\u30FC\u30C9 = m.\u9867\u5BA2\u30B3\u30FC\u30C9;\r\n```\r\n\r\n> **1 \u7D50\u679C\u30BB\u30C3\u30C8\u306B\u307E\u3068\u3081\u308B\u7406\u7531**: \u30D7\u30E9\u30B0\u30A4\u30F3 UI \u306F**\u6700\u5F8C\u306B\u7D50\u679C\u3092\u8FD4\u3057\u305F\u6587\u3060\u3051**\u3092\u8868\u793A\u3059\u308B\u305F\u3081\u3001`SELECT COUNT(*)` \u3092 2 \u672C\u4E26\u3079\u308B\u3068\u4E21\u65B9\u3092\u540C\u6642\u306B\u898B\u3089\u308C\u307E\u305B\u3093\u3002LEFT JOIN \u3067 1 \u884C\u306B\u307E\u3068\u3081\u308B\u3068\u5168\u5165\u53E3\u3067\u540C\u3058\u898B\u3048\u65B9\u306B\u306A\u308A\u307E\u3059\u3002`COUNT(m.\u9867\u5BA2\u30B3\u30FC\u30C9)` \u304C\u300C\u30DE\u30B9\u30BF\u306B\u30DE\u30C3\u30C1\u3057\u305F\u4EF6\u6570\uFF08\uFF1Dupdates\uFF09\u300D\u306B\u306A\u308B\u306E\u306F [\xA78 \u96C6\u8A08\u95A2\u6570](ksql_language_reference.md#8-group-by--\u96C6\u8A08\u95A2\u6570) \u306E\u300C`COUNT(\u30D5\u30A3\u30FC\u30EB\u30C9)` \u306F\u7A7A\u6587\u5B57\u30FBNULL \u3092\u30B9\u30AD\u30C3\u30D7\u300D\u4ED5\u69D8\u306B\u3088\u308A\u307E\u3059\u3002\r\n\r\n### \u5024\u306E\u59A5\u5F53\u6027\u3082\u5148\u306B\u898B\u308B\uFF08`VALIDATE ONLY`\u30FBv2.13.0\uFF09\r\n\r\n\u4EF6\u6570\u30B2\u30FC\u30C8\u306F\u300C\u4F55\u4EF6\u304B\u300D\u3057\u304B\u898B\u307E\u305B\u3093\u3002**\u5FC5\u9808\u30FB\u578B\u30FB\u7BC4\u56F2\u30FB\u6587\u5B57\u5217\u9577\u30FB\u9078\u629E\u80A2\u30FBUPSERT \u30AD\u30FC**\u304C\u901A\u308B\u304B\u306F `VALIDATE ONLY` \u3067\u66F8\u304D\u8FBC\u307F\u30BC\u30ED\u306E\u307E\u307E\u5168\u884C\u691C\u8A3C\u3067\u304D\u307E\u3059\uFF08[\xA717.1](ksql_language_reference.md#171-validate-only\u66F8\u304D\u8FBC\u307F\u524D\u691C\u8A3C)\uFF09\u3002\r\n\r\n```sql\r\nCREATE TEMP TABLE #tgt AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n\r\n-- \u66F8\u304D\u8FBC\u307E\u305A\u306B\u5168\u884C\u691C\u8A3C\u3002#err \u306B 1 \u884C = 1 \u30A8\u30E9\u30FC\uFF081 \u884C\u306B\u8907\u6570\u30A8\u30E9\u30FC\u306A\u3089\u8907\u6570\u884C\uFF09\r\nUPSERT INTO APP200 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM #tgt\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\nVALIDATE ONLY INTO #err;\r\n\r\n-- \u3069\u306E\u30AD\u30FC\u304C\u306A\u305C\u843D\u3061\u308B\u304B\u3092 1 \u884C\u306B\u307E\u3068\u3081\u3066\u78BA\u8A8D\uFF08GROUP_CONCAT \u306F v2.15.0\uFF09\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, GROUP_CONCAT($err_message SEPARATOR ' / ') AS \u30A8\u30E9\u30FC\u5185\u5BB9\r\nFROM #err GROUP BY \u9867\u5BA2\u30B3\u30FC\u30C9;\r\n```\r\n\r\n- `VALIDATE ONLY` \u306F **read-only \u6271\u3044**\u3067\u3001`ksql_query` / CLI \u304B\u3089 DML \u627F\u8A8D\u306A\u3057\u306B\u5B9F\u884C\u3067\u304D\u307E\u3059\uFF08\u66F8\u304D\u8FBC\u307F 0 \u4EF6\uFF09\u3002\r\n- \u305F\u3060\u3057**\u5B8C\u5168\u306A\u5165\u529B\u3092\u8981\u6C42**\u3059\u308B\u305F\u3081\u3001`truncate` \u8A2D\u5B9A\u306F\u5E38\u306B `error` \u3078\u4E0A\u66F8\u304D\u3055\u308C\u307E\u3059\u3002\r\n- **\u901A\u904E\u306F kintone \u306E\u66F8\u304D\u8FBC\u307F\u6210\u529F\u3092\u4FDD\u8A3C\u3057\u307E\u305B\u3093**\uFF08\u6A29\u9650\u30FB\u7AF6\u5408\u30FB\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA JS \u306A\u3069\u3001\u30ED\u30FC\u30AB\u30EB\u3067\u5224\u5B9A\u3067\u304D\u306A\u3044\u8981\u56E0\u304C\u3042\u308B\u305F\u3081\uFF09\u3002\r\n\r\n> **\u78BA\u8A8D\u624B\u6BB5\u306E\u5F79\u5272\u5206\u62C5**: \u69CB\u6587\u30FB\u9759\u7684\u691C\u67FB \u2192 `ksql_validate`\uFF08kintone\u975E\u30A2\u30AF\u30BB\u30B9\uFF09\uFF0F\u5B9F\u884C\u8A08\u753B\uFF08**\u30D5\u30A9\u30FC\u30E0\u5B9A\u7FA9\u3068\u5FC5\u8981\u6642\u306E\u30D7\u30ED\u30BB\u30B9\u72B6\u614Bmetadata\u3060\u3051\u3092\u53D6\u5F97\u3057\u3001\u30EC\u30B3\u30FC\u30C9\u53D6\u5F97\u30FB\u66F8\u8FBC\u307F\u306A\u3057**\uFF09\u2192 `ksql_explain` / `--dry-run`\uFF0F\u5B9F\u30C7\u30FC\u30BF\u306E\u4EF6\u6570 \u2192 \u4E0A\u306E R2 \u3092 `ksql_query` / CLI \u3067**\u5B9F\u884C**\uFF08read-only\uFF09\uFF0F**\u5024\u306E\u59A5\u5F53\u6027** \u2192 `VALIDATE ONLY`\u3002\r\n>\r\n> **`ksql_validate` \u306F\u300C\u5B9F\u884C\u3067\u304D\u308B\u3053\u3068\u300D\u3092\u4FDD\u8A3C\u3057\u307E\u305B\u3093**\uFF08\u69CB\u6587\u30FB\u9759\u7684\u89E3\u6790\u306E\u307F\uFF09\u3002\u305F\u3068\u3048\u3070 `UPDATE \u2026 WHERE $id IN (SELECT \u2026 FROM #tmp)` \u306F `ksql_validate` \u304C `ok` \u3092\u8FD4\u3057\u307E\u3059\u304C\u3001\u5B9F\u884C\u6642\u306B `IN (SELECT ...) \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093` \u3067\u5931\u6557\u3057\u307E\u3059\uFF08\u4E0B\u8A18\u306E\u6CE8\u8A18\uFF09\u3002\u5B9F\u884C\u53EF\u5426\u306F read-only\uFF08`VALIDATE ONLY`\u30FB`SELECT`\uFF09\u3067\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n---", uri: "ksql://recipes/r2" }, r3: { heading: "R3. \u66F4\u65B0\u524D\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\uFF08`#before`\uFF09", text: "## R3. \u66F4\u65B0\u524D\u30B9\u30CA\u30C3\u30D7\u30B7\u30E7\u30C3\u30C8\uFF08`#before`\uFF09\r\n\r\n\u4E0A\u66F8\u304D\u3055\u308C\u308B\u524D\u306E\u30DE\u30B9\u30BF\u306E\u5024\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306B\u9000\u907F\u3057\u3001\u7D50\u679C\u306B\u542B\u3081\u307E\u3059\uFF08\u5DEE\u5206\u306E\u8A18\u9332\u30FB\u76EE\u8996\u78BA\u8A8D\u7528\uFF09\u3002\r\n\r\n```sql\r\nCREATE TEMP TABLE #tgt AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n\r\n-- \u66F4\u65B0\u5BFE\u8C61\u306E\u300C\u66F4\u65B0\u524D\u306E\u5024\u300D\u3092\u9000\u907F\uFF08$ \u59CB\u307E\u308A\u306E\u5217\u306F\u30A8\u30A4\u30EA\u30A2\u30B9\u3092\u4ED8\u3051\u308B\uFF09\r\nCREATE TEMP TABLE #before AS\r\nSELECT $id AS \u30EC\u30B3\u30FC\u30C9ID, \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP200\r\nWHERE \u9867\u5BA2\u30B3\u30FC\u30C9 IN (SELECT \u9867\u5BA2\u30B3\u30FC\u30C9 FROM #tgt);\r\n\r\n-- \u672C\u51E6\u7406\uFF08UPSERT \u2026 SELECT \u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u53C2\u7167\u53EF\uFF09\r\nUPSERT INTO APP200 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM #tgt\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9);\r\n\r\n-- \u9000\u907F\u3057\u305F\u66F4\u65B0\u524D\u306E\u5024\u3092\u78BA\u8A8D\uFF08\u30D0\u30C3\u30C1\u306F\u6700\u5F8C\u306E\u7D50\u679C\u30BB\u30C3\u30C8\u3092\u8868\u793A\uFF09\r\nSELECT * FROM #before;\r\n```\r\n\r\n\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306F\u30D0\u30C3\u30C1\u5185\u30B9\u30B3\u30FC\u30D7\uFF08\u547C\u3073\u51FA\u3057\u7D42\u4E86\u3067\u7834\u68C4\uFF09\u306A\u306E\u3067\u3001\u6052\u4E45\u4FDD\u5B58\u304C\u8981\u308B\u5834\u5408\u306F\u5225\u9014\u30A2\u30D7\u30EA\u3078 INSERT \u3057\u307E\u3059\u3002R1 \u306B\u7D44\u307F\u8FBC\u3080\u5834\u5408\u306F\u3001\u78BA\u4FDD\uFF08R1 \u306E 2\uFF09\u306E\u5F8C\u30FBUPSERT \u306E\u524D\u306B `#before` \u3092\u4F5C\u308A\u307E\u3059\u3002\r\n\r\n---", uri: "ksql://recipes/r3" }, r4: { heading: "R4. \u30D0\u30C3\u30C1\u5909\u6570\u306E\u6D3B\u7528\uFF08v2.1.0\uFF09", text: "## R4. \u30D0\u30C3\u30C1\u5909\u6570\u306E\u6D3B\u7528\uFF08v2.1.0\uFF09\r\n\r\n- **\u6642\u523B\u56FA\u5B9A**: `SET @now = NOW();` \u2026 \u4EE5\u964D\u306E\u3059\u3079\u3066\u306E\u6587\u3067\u540C\u3058\u6642\u523B\uFF08`NOW()` \u3092\u6587\u3054\u3068\u306B\u8A55\u4FA1\u3059\u308B\u3068\u5024\u304C\u3076\u308C\u308B\uFF09\u3002**1a \u3067\u306F\u5909\u6570\u304B\u3089\u5909\u6570\u3078\u306E\u4EE3\u5165\uFF08`SET @b = @a`\uFF09\u306F\u3067\u304D\u306A\u3044**\u305F\u3081\u3001\u540C\u3058\u5024\u3092\u8907\u6570\u7528\u9014\u306B\u4F7F\u3046\u306A\u3089\u540C\u3058 `@now` \u3092\u4F7F\u3044\u56DE\u3057\u307E\u3059\u3002\r\n- **\u6761\u4EF6\u5024\u306E DRY \u5316**:\r\n ```sql\r\n SET @cutoff = TODAY();\r\n DELETE FROM APP100 WHERE \u4F5C\u6210\u65E5\u6642 < @cutoff AND \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u51E6\u7406\u6E08');\r\n ```\r\n \u3053\u306E DELETE \u306F**\u540C\u4E00\u5B9F\u884C\u306E\u4E2D\u3067\u306F\u51AA\u7B49**\uFF08`@cutoff` \u306F\u305D\u306E\u5B9F\u884C\u3067\u56FA\u5B9A\uFF09\u3002\u305F\u3060\u3057 `TODAY()` \u306F\u30D0\u30C3\u30C1\u3054\u3068\u306B\u518D\u8A55\u4FA1\u3055\u308C\u308B\u305F\u3081\u3001**\u7FCC\u65E5\u306E\u30EA\u30E9\u30F3\u3067\u306F\u5BFE\u8C61\u7BC4\u56F2\u304C 1 \u65E5\u5E83\u304C\u308A\u307E\u3059**\uFF08\u540C\u3058 cutoff \u306B\u5BFE\u3057\u3066\u306F\u51AA\u7B49\u3060\u304C\u3001\u65E5\u3092\u307E\u305F\u3044\u3067\u540C\u3058\u5BFE\u8C61\u96C6\u5408\u3092\u4FDD\u8A3C\u3057\u306A\u3044\uFF09\u3002\u53B3\u5BC6\u306B\u540C\u3058\u5BFE\u8C61\u3092\u518D\u73FE\u3059\u308B\u306A\u3089\u56FA\u5B9A\u306E\u65E5\u4ED8\u30EA\u30C6\u30E9\u30EB\u3092\u4F7F\u3046\u3002\r\n- **\u30C1\u30A7\u30C3\u30AF\u30DC\u30C3\u30AF\u30B9/\u8907\u6570\u9078\u629E\u30D5\u30A3\u30FC\u30EB\u30C9**: `=` \u3092\u4F7F\u3048\u306A\u3044\u30D5\u30A3\u30FC\u30EB\u30C9\u306F `IN (@\u5909\u6570)` \u3067\uFF08v2.1.0\uFF09\u3002\r\n ```sql\r\n SET @a = 'A'; SET @b = 'B';\r\n SELECT \u9867\u5BA2No FROM APP100 WHERE \u9867\u5BA2\u30E9\u30F3\u30AF IN (@a, @b);\r\n ```\r\n- **\u30D0\u30C3\u30C1\u7531\u6765\u30E9\u30D9\u30EB\u3068\u914D\u5217\u6761\u4EF6**: 1 \u3064\u306E\u914D\u5217\u3092\u8907\u6570\u6587\u3067\u4F7F\u3044\u56DE\u3057\u3001\u51E6\u7406\u30E9\u30D9\u30EB\u3092\u7D50\u679C\u3078\u4ED8\u3051\u308B\u3002\r\n ```sql\r\n SET @batch = NOW();\r\n SET @ranks = ['A', 'B'];\r\n SELECT @batch AS \u30D0\u30C3\u30C1ID, \u9867\u5BA2No FROM APP100 WHERE \u9867\u5BA2\u30E9\u30F3\u30AF IN @ranks;\r\n ```\r\n \u7A7A\u914D\u5217\u306E `IN @ranks` \u306F 0 \u4EF6\u3001`NOT IN @ranks` \u306F\u5168\u4EF6\u6761\u4EF6\u306B\u306A\u308B\u3002\u66F4\u65B0\u7CFB\u3067\u6700\u7D42 WHERE \u304C\u5168\u4EF6\u6761\u4EF6\u3078\u7C21\u7D04\u3055\u308C\u308B\u5834\u5408\u306F\u5B89\u5168\u306E\u305F\u3081\u62D2\u5426\u3055\u308C\u308B\u3002\r\n- **\u4EF6\u6570\u30B2\u30FC\u30C8\u306E DRY \u5316\uFF08\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u4EE3\u5165\u30FBv2.3.0\uFF1DPhase 1b\uFF09**: `SET @cnt = (SELECT COUNT(*) ...)` \u3067\u4EF6\u6570\u3092**\u4E00\u5EA6\u3060\u3051**\u53D6\u5F97\u3057\u3001\u30B2\u30FC\u30C8\u30FB\u8A18\u9332\u30FB\u5F8C\u7D9A\u6761\u4EF6\u3067\u4F7F\u3044\u56DE\u3059\u3002\r\n ```sql\r\n SET @cnt = (SELECT COUNT(*) FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406'));\r\n ASSERT @cnt BETWEEN 0 AND 10000; -- \u60F3\u5B9A\u5916\u4EF6\u6570\u306A\u3089\u505C\u6B62\r\n UPDATE APP100 SET \u5BFE\u8C61\u4EF6\u6570\u30E1\u30E2 = @cnt WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n ```\r\n - \u30B5\u30D6\u30AF\u30A8\u30EA\u306F **SET \u6642\u306B 1 \u56DE\u3060\u3051\u5B9F\u884C**\uFF08\u8907\u6570\u6587\u3067 `@cnt` \u3092\u53C2\u7167\u3057\u3066\u3082\u518D\u5B9F\u884C\u3057\u306A\u3044\uFF09\u3002**\u5148\u884C\u3057\u3066\u4F5C\u6210\u3057\u305F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB**\uFF08`SET @cnt = (SELECT COUNT(*) FROM #tgt)`\uFF09\u3084**\u5148\u884C\u5909\u6570**\uFF08`... WHERE \u671F\u9650 < @cutoff`\uFF09\u3082\u53C2\u7167\u53EF\u3002\r\n - **1 \u884C 1 \u5217**\u304C\u5FC5\u9808\u3002`GROUP BY` \u306A\u3057\u306E\u96C6\u8A08\u306F 0 \u4EF6\u3067\u3082 1 \u884C\uFF08`COUNT` \u306F `0`\uFF09\u3092\u8FD4\u3059\u305F\u3081\u3001\u4EF6\u6570\u53D6\u5F97\u306F\u5DEE\u5206 0 \u4EF6\u3067\u3082\u6210\u7ACB\u3059\u308B\uFF08\xA78\uFF09\u3002SET \u306E\u8A55\u4FA1\u5931\u6557\u306F `continueOnError` \u306B\u95A2\u308F\u3089\u305A\u30D0\u30C3\u30C1\u505C\u6B62\uFF08fail-fast\uFF09\u3002\r\n - **R2 \u306E\u4E8B\u524D\u30B2\u30FC\u30C8\u3092 DRY \u5316**\u3059\u308B\u4F8B\uFF08`(SELECT COUNT(*) FROM #tgt)` \u3092\u76F4\u63A5\u66F8\u304F\u4EE3\u308F\u308A\u306B\uFF09:\r\n ```sql\r\n CREATE TEMP TABLE #tgt AS SELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D FROM APP100 WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n SET @cnt = (SELECT COUNT(*) FROM #tgt);\r\n ASSERT @cnt BETWEEN 1 AND 10000;\r\n ```\r\n- **\u5B9A\u578B\u30D0\u30C3\u30C1\u306E\u5916\u90E8\u30D1\u30E9\u30E1\u30FC\u30BF\u5316\uFF08v2.4.0\uFF1DPhase 1c\uFF09**: SQL \u5074\u3067\u65E2\u5B9A\u5024\u3092\u5BA3\u8A00\u3057\u3001CLI/MCP \u3060\u3051\u5FC5\u8981\u6642\u306B\u5DEE\u3057\u66FF\u3048\u308B\u3002\r\n ```sql\r\n DECLARE @since = '2026-01-01';\r\n SELECT \u9867\u5BA2No FROM APP100 WHERE \u767B\u9332\u65E5 >= @since;\r\n ```\r\n CLI \u306F `--var since=2026-07-01`\u3001MCP \u306F `variables: { \"since\": \"2026-07-01\" }`\u3002\u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u65E2\u5B9A\u5024\u3067\u540C\u3058 SQL \u3092\u5B9F\u884C\u3059\u308B\u3002`--var` \u306F\u79D8\u5BC6\u60C5\u5831\u306B\u306F\u4F7F\u7528\u3057\u306A\u3044\u3002\r\n\r\n\u5909\u6570\u306E\u8A73\u7D30\u30FB\u5236\u7D04\u306F\u8A00\u8A9E\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9 [\xA725 \u30D0\u30C3\u30C1\u5909\u6570](ksql_language_reference.md#25-\u30D0\u30C3\u30C1\u5B9F\u884C\u3068\u4E00\u6642\u30C6\u30FC\u30D6\u30EB) \u3092\u53C2\u7167\u3002\r\n\r\n---", uri: "ksql://recipes/r4" }, r5: { heading: "R5. \u30EA\u30C6\u30E9\u30EB\u5024\u30EA\u30B9\u30C8\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u5316\u3057\u3066\u4E00\u62EC\u51E6\u7406", text: "## R5. \u30EA\u30C6\u30E9\u30EB\u5024\u30EA\u30B9\u30C8\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u5316\u3057\u3066\u4E00\u62EC\u51E6\u7406\r\n\r\n\u5916\u90E8\uFF08CSV\u30FB\u5225\u30B7\u30B9\u30C6\u30E0\uFF09\u7531\u6765\u306E **\u56FA\u5B9A\u30EA\u30B9\u30C8**\u3092 **`FROM` \u306A\u3057\u306E `SELECT \u2026 UNION ALL \u2026`** \u3067\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306B\u5B9F\u4F53\u5316\u3057\u3001\u30B2\u30FC\u30C8 \u2192 \u53D6\u308A\u8FBC\u307F\uFF08`UPSERT \u2026 SELECT`\uFF09\u3059\u308B\u3002\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306F\u3001**`ASSERT` \u304B\u3089\u306F `IN` \u30B5\u30D6\u30AF\u30A8\u30EA\uFF0F`COUNT`** \u3067\u3001**`INSERT \u2026 SELECT` / `UPSERT \u2026 SELECT` \u304B\u3089\u306F `FROM` \u30BD\u30FC\u30B9**\u3068\u3057\u3066\u518D\u5229\u7528\u3059\u308B\u3002\r\n\r\n```sql\r\n-- 1) \u5916\u90E8\u30EA\u30B9\u30C8\u3092\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306B\u5B9F\u4F53\u5316\uFF08\u66F8\u304D\u8FBC\u307F\u53EF\u80FD\u30AD\u30FC\u300C\u53D6\u5F15\u5148\u30B3\u30FC\u30C9\u300D\u3068\u5024\u3092\u6301\u3064\uFF09\r\nCREATE TEMP TABLE #incoming AS\r\n SELECT '1001' AS \u53D6\u5F15\u5148\u30B3\u30FC\u30C9, '\u5B8C\u4E86' AS \u72B6\u614B\r\n UNION ALL SELECT '1005', '\u5B8C\u4E86'\r\n UNION ALL SELECT '1012', '\u5B8C\u4E86';\r\n\r\n-- 2) \u4E8B\u524D\u30B2\u30FC\u30C8: \u53D6\u308A\u8FBC\u307F\u4EF6\u6570\u3092\u78BA\u8A8D\uFF08ASSERT \u306F COUNT \u3067 #t \u3092\u53C2\u7167\uFF09\r\nASSERT (SELECT COUNT(*) FROM #incoming) BETWEEN 1 AND 1000;\r\n\r\n-- 3) \u53D6\u308A\u8FBC\u307F: \u66F8\u304D\u8FBC\u307F\u53EF\u80FD\u30AD\u30FC\u3067\u767B\u9332/\u66F4\u65B0\uFF08UPSERT \u2026 SELECT \u306F #t \u3092 FROM \u30BD\u30FC\u30B9\u306B\uFF09\r\nUPSERT INTO APP100 (\u53D6\u5F15\u5148\u30B3\u30FC\u30C9, \u72B6\u614B)\r\n SELECT \u53D6\u5F15\u5148\u30B3\u30FC\u30C9, \u72B6\u614B FROM #incoming\r\n ON DUPLICATE (\u53D6\u5F15\u5148\u30B3\u30FC\u30C9);\r\n```\r\n\r\n- **DRY**: \u5916\u90E8\u30EA\u30B9\u30C8\u3092 `#incoming` \u306E 1 \u7B87\u6240\u306B\u96C6\u7D04\u3057\u3001`ASSERT`\uFF08`COUNT` / `IN` \u30B5\u30D6\u30AF\u30A8\u30EA\uFF09\u3068 `UPSERT \u2026 SELECT`\uFF08`FROM` \u30BD\u30FC\u30B9\uFF09\u304B\u3089\u518D\u5229\u7528\u3059\u308B\u3002\r\n- **`UPSERT` \u306B\u306F\u30AD\u30FC\u304C\u5FC5\u9808**: `ON DUPLICATE (\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9)` \u304C\u5FC5\u8981\u3067\u3001\u30AD\u30FC\u306F**\u30A2\u30D7\u30EA\u5074\u306E\u66F8\u304D\u8FBC\u307F\u53EF\u80FD\u30D5\u30A3\u30FC\u30EB\u30C9**\uFF08\u4F8B: `\u53D6\u5F15\u5148\u30B3\u30FC\u30C9` / `\u5916\u90E8ID`\uFF09\u3002**\u30B7\u30B9\u30C6\u30E0\u30D5\u30A3\u30FC\u30EB\u30C9 `$id` \u306F UPSERT \u30AD\u30FC\u306B\u3067\u304D\u306A\u3044**\u3002\r\n- **\u91CD\u8981\u306A\u5236\u7D04 \u2014 `UPDATE` / `DELETE` \u306E `WHERE` \u306B `IN (SELECT \u2026)` \u306F\u66F8\u3051\u306A\u3044**\uFF08`\u2026 WHERE $id IN (SELECT id FROM #t)` \u306F**\u5B9F\u884C\u6642**\u306B `IN (SELECT ...) \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093`\u3002\u6CE8\u610F\u306E\u300C\u30B5\u30D6\u30AF\u30A8\u30EA\u53C2\u7167\u306E\u975E\u5BFE\u79F0\u300D\u53C2\u7167\uFF09\u3002**\u5BFE\u8C61\u30A2\u30D7\u30EA\u306E\u65E2\u5B58\u884C\u3092 `$id` \u3067\u66F4\u65B0/\u524A\u9664**\u3057\u305F\u3044\u5834\u5408\u306F\u3001`UPDATE APP100 SET \u72B6\u614B='\u5B8C\u4E86' WHERE $id IN ('1001','1005','1012')` \u306E\u3088\u3046\u306B **`UPDATE` / `DELETE` \u5074\u3067\u306F\u30EA\u30B9\u30C8\u3092\u76F4\u63A5 `IN (...)` \u306B\u518D\u63B2**\u3059\u308B\uFF08\u3053\u306E\u7D4C\u8DEF\u3067\u306F\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306E DRY \u306F\u52B9\u304B\u306A\u3044\uFF09\u3002**\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u306E\u5024\u3067\u66F4\u65B0\u3059\u308B**\u306A\u3089 `UPDATE \u2026 FROM`\uFF08v2.12.0\u30FBR6\uFF09\u304C\u4F7F\u3048\u308B\u3002\r\n- **\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\uFF08\u81EA\u52D5\u30D0\u30A4\u30F3\u30C9\u3067\u306F\u306A\u3044\uFF09**: \u4E0A\u8A18\u306E\u5024\u306F **SQL \u6587\u4E2D\u306B\u30EA\u30C6\u30E9\u30EB\u3068\u3057\u3066\u8A18\u8FF0**\u3057\u3066\u304A\u308A\u3001kSQL \u304C\u5916\u90E8\u30EA\u30B9\u30C8\u3092\u81EA\u52D5\u3067\u30D0\u30A4\u30F3\u30C9\u3059\u308B\u6A5F\u80FD\u3067\u306F\u306A\u3044\u3002\u5916\u90E8\u5024\u304B\u3089 SQL \u3092\u751F\u6210\u3059\u308B\u5834\u5408\u306F\u3001**ID \u3092\u6570\u5B57\u3060\u3051\u306B\u691C\u8A3C**\u3059\u308B\u304B\u3001**\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u306E `'` \u3092 `''` \u306B\u30A8\u30B9\u30B1\u30FC\u30D7**\u3059\u308B\u3053\u3068\uFF08\u8AA4\u308C\u3070\u30A4\u30F3\u30B8\u30A7\u30AF\u30B7\u30E7\u30F3\u304C\u8D77\u3053\u308A\u5F97\u308B\uFF09\u3002\r\n- **kintone \u5185\u304B\u3089\u5C0E\u3051\u308B\u96C6\u5408**\u306A\u3089 `#incoming` \u3092\u4F7F\u308F\u305A\u76F4\u63A5 `IN (SELECT \u2026 FROM APPxxx WHERE \u2026)` \u306E\u65B9\u304C\u7C21\u5358\u3002R5 \u306F **kintone \u5916\u7531\u6765\u306E\u56FA\u5B9A\u30EA\u30B9\u30C8**\u304C\u5BFE\u8C61\u3002\r\n- **\u524D\u63D0\u30D0\u30FC\u30B8\u30E7\u30F3**: `CREATE TEMP TABLE AS ` \u306E\u5B9F\u4F53\u5316\u306F **v2.10.0 \u4EE5\u964D**\uFF08\u305D\u308C\u4EE5\u524D\u306F 0 \u884C\u306B\u306A\u308B\u4E0D\u5177\u5408\u304C\u3042\u3063\u305F\uFF09\u3002\r\n\r\n---", uri: "ksql://recipes/r5" }, r6: { heading: "R6. \u4E0D\u826F\u30C7\u30FC\u30BF\u3092\u9694\u96E2\u3057\u3066\u6B8B\u308A\u3092\u6D41\u3059\uFF08`ON ERROR SKIP`\u30FBv2.13.0\uFF09", text: "## R6. \u4E0D\u826F\u30C7\u30FC\u30BF\u3092\u9694\u96E2\u3057\u3066\u6B8B\u308A\u3092\u6D41\u3059\uFF08`ON ERROR SKIP`\u30FBv2.13.0\uFF09\r\n\r\nR1 \u306F fail-fast \u3067\u3001**1 \u4EF6\u306E\u4E0D\u826F\u30C7\u30FC\u30BF\u304C\u30D0\u30C3\u30C1\u5168\u4F53\u3092\u6B62\u3081\u307E\u3059**\u3002\u591C\u9593\u306E\u7121\u4EBA\u30D0\u30C3\u30C1\u3067\u306F\u300C\u4E0D\u826F\u884C\u3060\u3051\u9664\u3051\u3066\u6B8B\u308A\u306F\u6D41\u3057\u3001\u7FCC\u671D\u306B\u539F\u56E0\u3092\u898B\u308B\u300D\u307B\u3046\u304C\u671B\u307E\u3057\u3044\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002`ON ERROR SKIP INTO #err` \u306F\u3001**\u66F8\u304D\u8FBC\u307F\u524D\u306E\u30ED\u30FC\u30AB\u30EB\u691C\u8A3C\uFF08\u5FC5\u9808\u30FB\u578B\u30FB\u7BC4\u56F2\u30FB\u6587\u5B57\u5217\u9577\u30FB\u9078\u629E\u80A2\u30FB\u30AD\u30FC\uFF09\u306B\u843D\u3061\u305F\u884C\u3060\u3051**\u3092 `#err` \u3078\u9694\u96E2\u3057\u3001\u5408\u683C\u884C\u3060\u3051\u3092\u66F8\u304D\u8FBC\u307F\u307E\u3059\u3002\r\n\r\n```sql\r\nSET @now = NOW();\r\n\r\n-- 1) \u78BA\u4FDD\uFF08R1 \u3068\u540C\u3058 claim-first\u3002\u76F4\u63A5\u6761\u4EF6\u3067\u66F4\u65B0\uFF09\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u51E6\u7406\u4E2D', \u30D0\u30C3\u30C1ID = @now, \u78BA\u4FDD\u65E5\u6642 = @now\r\nWHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n\r\nCREATE TEMP TABLE #tgt AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, \u4F4F\u6240 FROM APP100\r\nWHERE \u30D0\u30C3\u30C1ID = @now AND \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u51E6\u7406\u4E2D');\r\n\r\nASSERT (SELECT COUNT(*) FROM #tgt) BETWEEN 0 AND 10000;\r\n\r\n-- 2) \u672C\u51E6\u7406: NG \u884C\u306F #err \u3078\u9694\u96E2\u3057\u3001\u5408\u683C\u884C\u3060\u3051\u66F8\u304F\u3002\u9694\u96E2\u304C 100 \u884C\u3092\u8D85\u3048\u305F\u3089\u4F55\u3082\u66F8\u304B\u305A\u505C\u6B62\r\nUPSERT INTO APP200 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, \u4F4F\u6240)\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, \u9867\u5BA2\u540D, \u4F4F\u6240 FROM #tgt\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9)\r\nON ERROR SKIP INTO #err REJECT LIMIT 100;\r\n\r\n-- 3) \u30A8\u30E9\u30FC\u884C\u306E\u66F8\u304D\u623B\u3057: \u696D\u52D9\u30AD\u30FC\u5358\u4F4D\u306B\u5168\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u9023\u7D50\u3057\u3066 1 \u884C\u5316\r\nCREATE TEMP TABLE #err_summary AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9, GROUP_CONCAT($err_message SEPARATOR ' / ') AS \u30A8\u30E9\u30FC\u5185\u5BB9\r\nFROM #err GROUP BY \u9867\u5BA2\u30B3\u30FC\u30C9;\r\n\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u30A8\u30E9\u30FC', \u30A8\u30E9\u30FC\u5185\u5BB9 = e.\u30A8\u30E9\u30FC\u5185\u5BB9, \u51E6\u7406\u65E5\u6642 = @now\r\nFROM #err_summary e\r\nWHERE APP100.\u9867\u5BA2\u30B3\u30FC\u30C9 = e.\u9867\u5BA2\u30B3\u30FC\u30C9 AND APP100.\u30D0\u30C3\u30C1ID = @now;\r\n\r\n-- 4) \u6B63\u5E38\u884C\u306E\u5B8C\u4E86: #err \u306B\u7121\u3044\u696D\u52D9\u30AD\u30FC\u3092 temp \u3067\u78BA\u5B9A\u3057\u3066\u304B\u3089\u66F4\u65B0\r\nCREATE TEMP TABLE #ok AS\r\nSELECT \u9867\u5BA2\u30B3\u30FC\u30C9 FROM #tgt\r\nWHERE \u9867\u5BA2\u30B3\u30FC\u30C9 NOT IN (SELECT \u9867\u5BA2\u30B3\u30FC\u30C9 FROM #err);\r\n\r\nUPDATE APP100\r\nSET \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 = '\u51E6\u7406\u6E08', \u51E6\u7406\u65E5\u6642 = @now\r\nFROM #ok o\r\nWHERE APP100.\u9867\u5BA2\u30B3\u30FC\u30C9 = o.\u9867\u5BA2\u30B3\u30FC\u30C9 AND APP100.\u30D0\u30C3\u30C1ID = @now;\r\n```\r\n\r\n**\u306A\u305C\u3053\u306E\u5F62\u304B**\r\n\r\n- **3) \u3068 4) \u304C `UPDATE \u2026 FROM`\uFF08v2.12.0 / \u696D\u52D9\u30AD\u30FC\u7D50\u5408\u306F v2.13.0\uFF09**: `#err` \u306F UPSERT \u306E**\u5165\u529B\u30DA\u30A4\u30ED\u30FC\u30C9\u5217\u3057\u304B\u6301\u305F\u305A**\u3001\u5DEE\u5206\u30A2\u30D7\u30EA\u306E `$id` \u3092\u6301\u3061\u307E\u305B\u3093\u3002\u305D\u306E\u305F\u3081 `$id` \u7D50\u5408\u3067\u306F\u66F8\u304D\u623B\u305B\u305A\u3001**\u696D\u52D9\u30AD\u30FC\u7D50\u5408**\u304C\u5FC5\u8981\u3067\u3059\u3002\r\n- **`AND APP100.\u30D0\u30C3\u30C1ID = @now` \u3092\u5FC5\u305A\u4ED8\u3051\u308B**: `UPDATE \u2026 FROM` \u306F\u7D50\u5408\u7B49\u5024\u3068\u30BF\u30FC\u30B2\u30C3\u30C8\u7D5E\u308A\u8FBC\u307F\u3092\u4E21\u65B9\u66F8\u3051\u307E\u3059\u3002\u3053\u308C\u304C\u7121\u3044\u3068\u3001**\u4ECA\u56DE\u306E\u30D0\u30C3\u30C1\u304C\u78BA\u4FDD\u3057\u3066\u3044\u306A\u3044\u540C\u4E00\u30AD\u30FC\u306E\u884C\u307E\u3067\u66F4\u65B0**\u3055\u308C\u5F97\u307E\u3059\u3002\r\n- **4) \u306F `#ok` \u3092 `SELECT` \u3067\u5148\u306B\u78BA\u5B9A\u3055\u305B\u308B**: `UPDATE \u2026 WHERE \u9867\u5BA2\u30B3\u30FC\u30C9 NOT IN (SELECT \u2026 FROM #err)` \u3068\u66F8\u304D\u305F\u304F\u306A\u308A\u307E\u3059\u304C\u3001**DML \u306E `WHERE` \u306B `IN (SELECT \u2026)` \u306F\u66F8\u3051\u307E\u305B\u3093**\uFF08\u4E0B\u8A18\u306E\u6CE8\u8A18\uFF09\u3002`NOT IN (SELECT \u2026)` \u306F **`SELECT` \u6587\uFF08`CREATE TEMP TABLE \u2026 AS SELECT`\uFF09\u306A\u3089\u4F7F\u3048\u307E\u3059**\u3002\r\n- **`GROUP_CONCAT` \u3067\u5168\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u6B8B\u3059\uFF08v2.15.0\uFF09**: 1 \u884C\u306B\u8907\u6570\u30A8\u30E9\u30FC\u304C\u3042\u308B\u3068 `#err` \u306F\u8907\u6570\u884C\u306B\u306A\u308A\u307E\u3059\u3002`UPDATE \u2026 FROM` \u306F**\u8907\u6570\u30DE\u30C3\u30C1\u3092\u5B9F\u884C\u524D\u30A8\u30E9\u30FC**\u306B\u3059\u308B\u305F\u3081\u3001\u696D\u52D9\u30AD\u30FC\u5358\u4F4D\u3078 1 \u884C\u5316\u304C\u5FC5\u9808\u3067\u3059\u3002`MIN($err_message)` \u3060\u3068\u4EE3\u8868 1 \u4EF6\u3057\u304B\u6B8B\u308A\u307E\u305B\u3093\u304C\u3001`GROUP_CONCAT` \u306A\u3089\u5168\u4EF6\u3092\u9023\u7D50\u3067\u304D\u307E\u3059\u3002\r\n- **`REJECT LIMIT n`**: \u9694\u96E2\u304C n \u884C\u3092\u8D85\u3048\u305F\u3089**\u5168\u884C\u691C\u8A3C\u3092\u7D42\u3048\u305F\u3046\u3048\u3067\u66F8\u304D\u8FBC\u307F\u30BC\u30ED\u3067\u505C\u6B62**\u3057\u307E\u3059\uFF08\u90E8\u5206\u66F8\u304D\u8FBC\u307F\u306F\u8D77\u304D\u307E\u305B\u3093\uFF09\u3002`#err` \u306F\u7D50\u679C\u3068\u3057\u3066\u8FD4\u308B\u306E\u3067\u539F\u56E0\u8ABF\u67FB\u306B\u4F7F\u3048\u307E\u3059\u3002\u300C\u4E0D\u826F\u304C\u5927\u91CF\uFF1D\u4E0A\u6D41\u306E\u7570\u5E38\u300D\u3092\u691C\u77E5\u3059\u308B\u30B2\u30FC\u30C8\u3067\u3059\u3002\r\n\r\n**\u9694\u96E2\u3055\u308C\u308B\u7BC4\u56F2\uFF08\u91CD\u8981\uFF09**\r\n\r\n- \u9694\u96E2\u3067\u304D\u308B\u306E\u306F **kSQL \u304C API \u9001\u4FE1\u524D\u306B\u30ED\u30FC\u30AB\u30EB\u3067\u5224\u5B9A\u3067\u304D\u308B\u30A8\u30E9\u30FC\u3060\u3051**\uFF08Tier 0\uFF09\u3067\u3059\u3002**kintone API \u306E\u5B9F\u884C\u6642\u30A8\u30E9\u30FC**\uFF08\u6A29\u9650\u30FB\u7AF6\u5408\u30FB\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA JS \u306B\u3088\u308B\u4FDD\u5B58\u62D2\u5426\u306A\u3069\uFF09\u306F**\u5F93\u6765\u3069\u304A\u308A fail-fast**\u3067\u3001\u884C\u5358\u4F4D\u306B\u9694\u96E2\u3055\u308C\u307E\u305B\u3093\u3002\r\n- \u9006\u306B\u3001\u30ED\u30FC\u30AB\u30EB\u691C\u8A3C\u306F**\u66F8\u304D\u8FBC\u307F\u7D4C\u8DEF\u3088\u308A\u53B3\u3057\u3044\u3053\u3068\u304C\u3042\u308A\u307E\u3059**\u3002\u691C\u8A3C\u3092\u901A\u3063\u3066\u3082\u66F8\u304D\u8FBC\u307F\u6210\u529F\u306F\u4FDD\u8A3C\u3055\u308C\u307E\u305B\u3093\u3002\r\n- **\u524D\u63D0\u30D0\u30FC\u30B8\u30E7\u30F3**: `ON ERROR SKIP` / `VALIDATE ONLY` / \u696D\u52D9\u30AD\u30FC\u7D50\u5408\u306F **v2.13.0 \u4EE5\u964D**\u3001`GROUP_CONCAT` \u3068 `#err` \u5217\u306E\u578B\u4F1D\u64AD\u306F **v2.15.0 \u4EE5\u964D**\u3002\r\n\r\n---", uri: "ksql://recipes/r6" }, r7: { heading: "R7. kintone \u306E REST API \u3068\u540C\u3058\u4E26\u3073\u3067\u5927\u91CF\u53D6\u5F97\u3059\u308B\uFF08`KORDER BY`\u30FBv3.0.0 / v3.1.0\uFF09", text: "## R7. kintone \u306E REST API \u3068\u540C\u3058\u4E26\u3073\u3067\u5927\u91CF\u53D6\u5F97\u3059\u308B\uFF08`KORDER BY`\u30FBv3.0.0 / v3.1.0\uFF09\r\n\r\nCSV \u9023\u643A\u3084\u7A81\u5408\u3067\u300C**kintone REST API \u306E\u4E26\u3073\uFF08\u578B\u5225\u9806\u5E8F\uFF09**\u300D\u304C\u8981\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002v3.0.0 \u4EE5\u964D\u3001\u901A\u5E38\u306E `ORDER BY` \u306F\u300C\u3069\u306E\u5B9F\u884C\u9762\uFF08CLI / MCP / \u30D7\u30E9\u30B0\u30A4\u30F3\uFF09\u3067\u3082\u30FB\u4F55\u5EA6\u5B9F\u884C\u3057\u3066\u3082\u540C\u3058\u7D50\u679C\u306B\u306A\u308B\u300D\u3088\u3046\u306B **kSQL \u304C\u578B\u3054\u3068\u306B\u5B9A\u7FA9\u3057\u305F\u4E26\u3073**\uFF08\u6570\u5024\u306F\u6570\u5024\u9806\u30FB\u6587\u5B57\u5217\u306F Unicode \u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u9806\u3002[\u8A00\u8A9E\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9 \xA710](ksql_language_reference.md#10-order-by)\uFF09\u3067\u4E26\u3079\u307E\u3059\u3002\u3053\u306E\u305F\u3081\u3001**kintone \u304C\u30D5\u30A3\u30FC\u30EB\u30C9\u578B\u3054\u3068\u306B\u6301\u3064\u72EC\u81EA\u306E\u4E26\u3073** \u2014 \u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3\u30FB\u30E9\u30B8\u30AA\u30DC\u30BF\u30F3\u306E\u9078\u629E\u80A2\u5B9A\u7FA9\u9806\u3001\u30B9\u30C6\u30FC\u30BF\u30B9\u306E\u30D7\u30ED\u30BB\u30B9\u5B9A\u7FA9\u9806\u306A\u3069 \u2014 \u3068\u306F\u4E00\u81F4\u3057\u306A\u3044\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002kintone \u5074\u306E\u4E26\u3073\u304C\u5FC5\u8981\u306A\u5834\u5408\u306F **`KORDER BY`** \u3092\u4F7F\u3044\u307E\u3059\u3002\u4E00\u89A7\u753B\u9762\u3068\u540C\u3058\u4E26\u3073\u306B**\u8FD1\u3065\u3051\u308B**\u306B\u306F\u3001\u753B\u9762\u3068\u540C\u3058\u30AD\u30FC\u30FB\u65B9\u5411\u3092\u6307\u5B9A\u3057\u3001\u540C\u5024\u7FA4\u306E\u9806\u5E8F\u306F\u6697\u9ED9\u4FDD\u8A3C\u3055\u308C\u306A\u3044\u305F\u3081**\u6700\u5F8C\u306E\u30AD\u30FC\u3078 `$id ASC` \u3092\u660E\u793A**\u3057\u307E\u3059\uFF08kSQL \u306F\u6697\u9ED9\u8FFD\u52A0\u3057\u307E\u305B\u3093\uFF09\u3002\r\n\r\n```sql\r\n-- kintone \u56FA\u6709\u9806\u306E\u307E\u307E\u5148\u982D 10,001 \u4EF6\uFF08v3.1.0 \u304B\u3089\u5358\u767A GET \u306B\u53CE\u307E\u3089\u306A\u3044\u7A93\u3082\u53EF\uFF09\r\nSELECT $id, \u90F5\u4FBF\u756A\u53F7, \u4F4F\u62401\r\nFROM APP730\r\nKORDER BY \u90F5\u4FBF\u756A\u53F7 ASC, $id ASC\r\nLIMIT 10001\r\n```\r\n\r\n- **`LIMIT` \u306F\u5FC5\u9808**\u3002**\u5358\u767A API \u306B\u306A\u308B\u306E\u306F `LIMIT \u2264 500` \u304B\u3064 `OFFSET \u2264 10000` \u304B\u3064 `LIMIT \u2264 maxRecords` \u306E 3 \u6761\u4EF6\u3092\u6E80\u305F\u3059\u5834\u5408**\u3067\u3001\u3053\u306E\u3068\u304D OFFSET \u306F\u30B5\u30FC\u30D0\u30FC\u304C\u8AAD\u307F\u98DB\u3070\u3059\u305F\u3081 `maxRecords` \u306E\u5F15\u304D\u4E0A\u3052\u306F\u4E0D\u8981\u3067\u3059\uFF08\u4F8B: `LIMIT 500 OFFSET 10000` \u306F `maxRecords=500` \u306E\u307E\u307E\u3067\u6210\u529F\uFF09\r\n- 3 \u6761\u4EF6\u304B\u3089\u5916\u308C\u308B\u7A93\u306F **Cursor API**\uFF08v3.1.0\uFF09\u3067 500 \u4EF6\u305A\u3064\u9023\u7D50\u3057\u307E\u3059\uFF08\u7D50\u679C\u9806\u306F raw API \u3068\u5B8C\u5168\u4E00\u81F4\u3059\u308B\u3053\u3068\u3092\u5B9F\u6E2C\u6E08\u307F\uFF09\u3002**Cursor \u306E\u3068\u304D\u3060\u3051**\u8D70\u67FB\u4EF6\u6570 `OFFSET + LIMIT` \u2264 \u5B9F\u884C\u6642 `maxRecords` \u304C\u6761\u4EF6\u306B\u306A\u308A\u307E\u3059\uFF08OFFSET \u5206\u3092 kSQL \u304C\u53D7\u4FE1\u3057\u3066\u8AAD\u307F\u6368\u3066\u308B\u305F\u3081\uFF09\u3002CLI/MCP \u306E\u65E2\u5B9A\u306F 500 \u306A\u306E\u3067\u3001\u4E0A\u306E\u4F8B\u306F `--max-records 10001`\uFF08MCP \u306F `maxRecords: 10001`\uFF09\u3078\u5F15\u304D\u4E0A\u3052\u307E\u3059\u3002\u8D85\u904E\u306F\u5B9F\u884C\u524D\u306E planning error\uFF08\u9ED9\u3063\u3066\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u305B\u3093\uFF09\r\n- \u30AB\u30FC\u30BD\u30EB\u306E\u5BFE\u8C61\u96C6\u5408\u306F\u4F5C\u6210\u6642\u70B9\u3067\u56FA\u5B9A\u3067\u3059\u304C**\u5024\u306F\u53D6\u5F97\u6642\u70B9**\u3067\u3059\u3002\u66F4\u65B0\u304C\u8D70\u308B\u6642\u9593\u5E2F\u306E\u5B9F\u884C\u306F\u907F\u3051\u3066\u304F\u3060\u3055\u3044\u3002\u30AB\u30FC\u30BD\u30EB\u67A0\uFF081 \u30C9\u30E1\u30A4\u30F3 10 \u500B\u306E\u5171\u6709\u30FB\u540C\u6642\u4E0A\u9650 `cursorMaxActive`\uFF09\u30FB\u518D\u8A66\u884C\u7981\u6B62\u30FBcleanup \u8B66\u544A\u306E\u8A73\u7D30\u306F [v3.1.0 \u79FB\u884C\u30AC\u30A4\u30C9](ksql_v3_1_migration_guide.md)\u3092\u53C2\u7167\r\n- \u6761\u4EF6: \u30C8\u30C3\u30D7\u30EC\u30D9\u30EB SELECT\u30FB\u5358\u4E00\u30A2\u30D7\u30EA\u30FBWHERE \u5B8C\u5168\u62BC\u3057\u4E0B\u3052\u30FB\u578B allowlist \u7B49\uFF08\u8A73\u7D30\u306F[\u8A00\u8A9E\u30EA\u30D5\u30A1\u30EC\u30F3\u30B9 \xA710](ksql_language_reference.md#10-order-by)\uFF09\r\n\r\n---", uri: "ksql://recipes/r7" }, r8: { heading: "R8. Shift_JIS \u3067\u51FA\u529B\u3067\u304D\u306A\u3044\u6F22\u5B57\u3092\u5909\u63DB\u3059\u308B\uFF08v3.2.0\uFF09", text: "## R8. Shift_JIS \u3067\u51FA\u529B\u3067\u304D\u306A\u3044\u6F22\u5B57\u3092\u5909\u63DB\u3059\u308B\uFF08v3.2.0\uFF09\r\n\r\ncli-kintone \u306E CSV \u3092 Shift_JIS \u3067\u51FA\u529B\u3059\u308B\u3068\u3001CP932 \u306B\u7121\u3044\u6F22\u5B57\u3092\u542B\u3080\u30EC\u30B3\u30FC\u30C9\u3067\u51FA\u529B\u30A8\u30E9\u30FC\u306B\u306A\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u3059\u3002`TRANSLATE` \u3092\u4F7F\u3044\u3001\u8A72\u5F53\u3059\u308B 40 \u5B57\u3092 Shift_JIS \u3067\u6271\u3048\u308B\u5B57\u4F53\u3078 1 \u5BFE 1 \u3067\u5909\u63DB\u3057\u307E\u3059\u3002\u5909\u63DB\u8868\u306F [\u8A08\u7B97\u5F0F\u30D7\u30E9\u30B0\u30A4\u30F3\u3067\u306E\u5B9F\u4F8B](https://qiita.com/rex0220/items/9db98b2cf027b686e0b5) \u3068\u540C\u3058\u3082\u306E\u3067\u3059\u3002\r\n\r\n| | \u5909\u63DB\u8868 |\r\n|---|---|\r\n| \u5909\u63DB\u5143 | `\u555E\u7130\u9DD7\u6451\u9EB4\u5653\u4FE0\u9830\u8EC0\u4FF1\u7E6B\u59F8\u9E7C\u5699\u6522\u{20B9F}\u7E61\u8523\u91AC\u87EC\u6414\u7626\u9A52\u7C1E\u5861\u985A\u79B1\u7006\u541E\u56CA\u525D\u6F51\u91B1\u5C5B\u5E77\u9EB5\u840A\u5C62\u6CAA\u881F` |\r\n| \u5909\u63DB\u5148 | `\u5516\u7114\u9D0E\u63B4\u9EB9\u5618\u4FA0\u982C\u8EAF\u5036\u7E4B\u598D\u9E78\u565B\u6505\u53F1\u7E4D\u848B\u91A4\u8749\u63BB\u75E9\u9A28\u7BAA\u586B\u985B\u7977\u6D9C\u5451\u56A2\u5265\u6E8C\u9197\u5C4F\u5E76\u9EBA\u83B1\u5C61\u6FFE\u874B` |\r\n\r\n```sql\r\nSELECT\r\n TRANSLATE(\u4F1A\u793E\u540D,\r\n '\u555E\u7130\u9DD7\u6451\u9EB4\u5653\u4FE0\u9830\u8EC0\u4FF1\u7E6B\u59F8\u9E7C\u5699\u6522\u{20B9F}\u7E61\u8523\u91AC\u87EC\u6414\u7626\u9A52\u7C1E\u5861\u985A\u79B1\u7006\u541E\u56CA\u525D\u6F51\u91B1\u5C5B\u5E77\u9EB5\u840A\u5C62\u6CAA\u881F',\r\n '\u5516\u7114\u9D0E\u63B4\u9EB9\u5618\u4FA0\u982C\u8EAF\u5036\u7E4B\u598D\u9E78\u565B\u6505\u53F1\u7E4D\u848B\u91A4\u8749\u63BB\u75E9\u9A28\u7BAA\u586B\u985B\u7977\u6D9C\u5451\u56A2\u5265\u6E8C\u9197\u5C4F\u5E76\u9EBA\u83B1\u5C61\u6FFE\u874B'\r\n ) AS \u4F1A\u793E\u540D,\r\n \u4F4F\u6240\r\nFROM APP100;\r\n```\r\n\r\n`\u{20B9F}` \u306F UTF-16 \u3067\u306F 2 \u30B3\u30FC\u30C9\u30E6\u30CB\u30C3\u30C8\u3067\u3059\u304C\u3001`TRANSLATE` \u306F\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\u5358\u4F4D\u3067\u5909\u63DB\u8868\u3092\u305D\u308D\u3048\u308B\u305F\u3081\u3001\u5F8C\u7D9A\u306E\u5BFE\u5FDC\u3082\u305A\u308C\u307E\u305B\u3093\u3002\u5909\u63DB\u5143\u3068\u5909\u63DB\u5148\u306E\u6587\u5B57\u6570\u304C\u7570\u306A\u308B\u5834\u5408\u306F\u3001\u6B20\u843D\u6587\u5B57\u3092\u9ED9\u3063\u3066\u524A\u9664\u305B\u305A `ArgumentError` \u3067\u505C\u6B62\u3057\u307E\u3059\u3002\u5909\u63DB\u5F8C\u306E SELECT \u7D50\u679C\u3092 cli-kintone \u306E CSV \u51FA\u529B\u5BFE\u8C61\u306B\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002\r\n\r\n**kintone \u5074\u306E\u5024\u305D\u306E\u3082\u306E\u3092\u5909\u63DB\u3057\u3066\u66F8\u304D\u623B\u3059\uFF08`UPDATE`\u30FBv3.2.0\u301C\uFF09**\r\n\r\nCSV \u51FA\u529B\u306E\u305F\u3073\u306B\u5909\u63DB\u3059\u308B\u306E\u3067\u306F\u306A\u304F\u3001\u30EC\u30B3\u30FC\u30C9\u306E\u5024\u81EA\u4F53\u3092 Shift_JIS \u3067\u6271\u3048\u308B\u5B57\u4F53\u3078\u305D\u308D\u3048\u305F\u3044\u5834\u5408\u306F `UPDATE` \u3067\u66F8\u304D\u623B\u3057\u307E\u3059\u3002\r\n\r\n\u5F62 A: \u5BFE\u8C61\u5168\u884C\u3092\u305D\u306E\u307E\u307E\u5909\u63DB\u3059\u308B\uFF081 \u6587\uFF09\r\n\r\n```sql\r\nUPDATE APP100\r\nSET \u4F1A\u793E\u540D = TRANSLATE(\u4F1A\u793E\u540D,\r\n '\u555E\u7130\u9DD7\u6451\u9EB4\u5653\u4FE0\u9830\u8EC0\u4FF1\u7E6B\u59F8\u9E7C\u5699\u6522\u{20B9F}\u7E61\u8523\u91AC\u87EC\u6414\u7626\u9A52\u7C1E\u5861\u985A\u79B1\u7006\u541E\u56CA\u525D\u6F51\u91B1\u5C5B\u5E77\u9EB5\u840A\u5C62\u6CAA\u881F',\r\n '\u5516\u7114\u9D0E\u63B4\u9EB9\u5618\u4FA0\u982C\u8EAF\u5036\u7E4B\u598D\u9E78\u565B\u6505\u53F1\u7E4D\u848B\u91A4\u8749\u63BB\u75E9\u9A28\u7BAA\u586B\u985B\u7977\u6D9C\u5451\u56A2\u5265\u6E8C\u9197\u5C4F\u5E76\u9EBA\u83B1\u5C61\u6FFE\u874B')\r\nWHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n```\r\n\r\n- \u89AA DML \u306E `WHERE` \u306B\u306F\u95A2\u6570\u3092\u66F8\u3051\u306A\u3044\u305F\u3081\u3001\u5F62 A \u306F WHERE \u6761\u4EF6\u306E**\u5168\u884C**\u3078 PUT \u3057\u307E\u3059\u3002\u5909\u63DB\u5BFE\u8C61\u306E\u5B57\u3092\u542B\u307E\u306A\u3044\u884C\u3082\u66F4\u65B0\u6271\u3044\u306B\u306A\u308A\u3001\u66F4\u65B0\u65E5\u6642\u304C\u5909\u308F\u308A\u901A\u77E5\u30FBWebhook\u30FB\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA JS \u304C\u767A\u706B\u3057\u5F97\u307E\u3059\uFF08R10 \u5F62 A \u3068\u540C\u3058\u6CE8\u610F\uFF09\u3002\u526F\u4F5C\u7528\u3092\u6291\u3048\u305F\u3044\u30FB\u30EA\u30E9\u30F3\u3057\u305F\u3044\u5834\u5408\u306F\u5F62 B \u3078\u3002\r\n\r\n\u5F62 B: \u5909\u63DB\u304C\u5FC5\u8981\u306A\u884C\u3060\u3051\u3078\u7D5E\u308B\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u7D4C\u7531\uFF09\r\n\r\n```sql\r\n-- \u5909\u63DB\u3059\u308B\u3068\u5024\u304C\u5909\u308F\u308B\u884C\uFF08\uFF1D\u5909\u63DB\u5BFE\u8C61\u5B57\u3092\u542B\u3080\u884C\uFF09\u3060\u3051\u3092\u5B9F\u4F53\u5316\r\nCREATE TEMP TABLE #sjis AS\r\n SELECT $id AS \u5BFE\u8C61id,\r\n TRANSLATE(\u4F1A\u793E\u540D, '\u555E\u2026\u881F', '\u5516\u2026\u874B') AS \u5909\u63DB\u5F8C\r\n FROM APP100\r\n WHERE \u4F1A\u793E\u540D <> TRANSLATE(\u4F1A\u793E\u540D, '\u555E\u2026\u881F', '\u5516\u2026\u874B');\r\nUPDATE APP100 SET \u4F1A\u793E\u540D = n.\u5909\u63DB\u5F8C FROM #sjis AS n WHERE APP100.$id = n.\u5BFE\u8C61id;\r\n```\r\n\r\n- `'\u555E\u2026\u881F'` / `'\u5516\u2026\u874B'` \u306F\u4E0A\u306E\u5168 40 \u5B57\uFF08\u5909\u63DB\u5143 / \u5909\u63DB\u5148\uFF09\u306E**\u7701\u7565\u8868\u8A18**\u3067\u3059\u3002\u5B9F\u969B\u306B\u306F\u7701\u7565\u305B\u305A\u5168\u5B57\u3092\u66F8\u304D\u307E\u3059\u3002\r\n- SELECT \u5074\u306E `WHERE` \u306B\u306F\u95A2\u6570\u3092\u66F8\u3051\u308B\u306E\u3067\u3001`\u4F1A\u793E\u540D <> TRANSLATE(\u2026)`\uFF08\uFF1D\u5909\u63DB\u3059\u308B\u3068\u5024\u304C\u5909\u308F\u308B\u884C\uFF09\u3060\u3051\u3092\u9078\u3079\u307E\u3059\u3002\u5BFE\u8C61 0 \u4EF6\u3067\u3082 `UPDATE \u2026 FROM` \u306F no-op \u3067\u5B8C\u8D70\u3057\u307E\u3059\uFF08\u30EA\u30E9\u30F3\u5B89\u5168\uFF09\u3002\r\n- \u66F8\u304D\u8FBC\u307F\u524D\u306E\u4E8B\u524D\u78BA\u8A8D\u306F\u672B\u5C3E\u306B `VALIDATE ONLY` \u3092\u4ED8\u3051\u308B\u3068\u3001\u66F8\u304D\u8FBC\u307F 0 \u3067\u691C\u8A3C\u3060\u3051\u3067\u304D\u307E\u3059\uFF08\u4F8B: `UPDATE APP100 SET \u4F1A\u793E\u540D = TRANSLATE(\u2026) WHERE \u2026 VALIDATE ONLY`\uFF09\u3002\r\n\r\n---", uri: "ksql://recipes/r8" }, r9: { heading: "R9. \u30C7\u30FC\u30BF\u54C1\u8CEA\u30C1\u30A7\u30C3\u30AF \u2014 \u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u30FB\u6587\u5B57\u6570\u4E88\u7B97\uFF08v3.2.0\uFF09", text: "## R9. \u30C7\u30FC\u30BF\u54C1\u8CEA\u30C1\u30A7\u30C3\u30AF \u2014 \u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u30FB\u6587\u5B57\u6570\u4E88\u7B97\uFF08v3.2.0\uFF09\r\n\r\n`LENGTH`\uFF08UTF-16 \u30B3\u30FC\u30C9\u30E6\u30CB\u30C3\u30C8\uFF1Dkintone \u306E\u300C\u6587\u5B57\u6570\u300D\uFF09\u3068 `LENGTH_CHAR`\uFF08\u30B3\u30FC\u30C9\u30DD\u30A4\u30F3\u30C8\uFF09\u306E**\u5DEE\u306F\u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u306E\u500B\u6570**\u3067\u3059\u3002\u7D75\u6587\u5B57\u3084 `\u{20B9F}`\u30FB`\u{20BB7}`\uFF08\u5E38\u7528\u6F22\u5B57\u30FB\u4EBA\u540D\u3067\u666E\u901A\u306B\u73FE\u308C\u308B\uFF09\u3092\u542B\u3080\u884C\u3092\u3001\u5916\u90E8\u9023\u643A\u306E\u524D\u306B\u6D17\u3044\u51FA\u305B\u307E\u3059\u3002\r\n\r\n```sql\r\n-- \u30B5\u30ED\u30B2\u30FC\u30C8\u30DA\u30A2\u3092\u542B\u3080\u884C\u3092\u691C\u51FA\uFF08\u5DEE = \u30DA\u30A2\u6570\uFF09\r\nSELECT $id, \u4F1A\u793E\u540D,\r\n LENGTH(\u4F1A\u793E\u540D) AS \u6587\u5B57\u6570,\r\n LENGTH(\u4F1A\u793E\u540D) - LENGTH_CHAR(\u4F1A\u793E\u540D) AS \u30DA\u30A2\u6570\r\nFROM APP100\r\nWHERE LENGTH(\u4F1A\u793E\u540D) - LENGTH_CHAR(\u4F1A\u793E\u540D) > 0\r\n```\r\n\r\n- SELECT \u306E `WHERE` \u306F\u95A2\u6570\u30FB\u7B97\u8853\u5F0F\u3092\u66F8\u3051\u307E\u3059\uFF08FULL_SCAN \u3067 JS \u8A55\u4FA1\uFF09\u3002**\u89AA DML \u306E `WHERE` \u306B\u306F\u66F8\u3051\u306A\u3044**\u70B9\u304C\u5BFE\u7167\u7684\u3067\u3059\uFF08R10\uFF09\r\n- `\xE9\xE9` \u306E\u3088\u3046\u306A\u300CUTF-8 \u3060\u3068 2 \u30D0\u30A4\u30C8\uFF0F1 \u30E6\u30CB\u30C3\u30C8\u300D\u306E\u6587\u5B57\u306F\u5DEE 0 \u306B\u306A\u308A\u8AA4\u691C\u77E5\u3057\u307E\u305B\u3093\uFF08\u30D0\u30A4\u30C8\u6570\u6BD4\u8F03\u3067\u306F\u539F\u7406\u7684\u306B\u5224\u5B9A\u3067\u304D\u306A\u304B\u3063\u305F\u30B1\u30FC\u30B9\uFF09\r\n- kintone \u306E `maxLength` \u306F UTF-16 \u3067\u6570\u3048\u308B\u305F\u3081\u3001**\u4E0A\u9650\u30C1\u30A7\u30C3\u30AF\u306F\u5F93\u6765\u3069\u304A\u308A `LENGTH`** \u3092\u4F7F\u3044\u307E\u3059\u3002\u300C\u4EBA\u304C\u6570\u3048\u308B\u6587\u5B57\u6570\u300D\u306B\u8FD1\u3044\u306E\u306F `LENGTH_CHAR` \u3067\u3059\uFF08IVS\u30FB\u7D50\u5408\u6587\u5B57\u30FBZWJ \u7D75\u6587\u5B57\u306F\u5BFE\u8C61\u5916\uFF09\r\n\r\n---", uri: "ksql://recipes/r9" }, r10: { heading: "R10. \u8868\u8A18\u306E\u6B63\u898F\u5316\u3092\u66F8\u304D\u623B\u3059\uFF08`UPDATE SET` \u306E\u6587\u5B57\u5217\u95A2\u6570\u30FBv3.2.0\uFF09", text: "## R10. \u8868\u8A18\u306E\u6B63\u898F\u5316\u3092\u66F8\u304D\u623B\u3059\uFF08`UPDATE SET` \u306E\u6587\u5B57\u5217\u95A2\u6570\u30FBv3.2.0\uFF09\r\n\r\nv3.2.0 \u304B\u3089\u6587\u5B57\u5217\u95A2\u6570\u3092 `UPDATE SET` \u306B\u76F4\u63A5\u66F8\u3051\u307E\u3059\uFF08\u5F93\u6765\u306F `CASE WHEN 1=1 THEN \u2026 ELSE \u2026 END` \u3067\u5305\u3080\u304B\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u7D4C\u7531\u304C\u5FC5\u8981\u3067\u3057\u305F\uFF09\u3002\r\n\r\n**\u5F62 A: \u5BFE\u8C61\u5168\u884C\u3092\u305D\u306E\u307E\u307E\u6B63\u898F\u5316\u3059\u308B\uFF081 \u6587\uFF09**\r\n\r\n```sql\r\n-- \u96FB\u8A71\u756A\u53F7\u306E\u30CF\u30A4\u30D5\u30F3\u30FB\u7A7A\u767D\u3092\u9664\u53BB\u3057\u3066\u66F8\u304D\u623B\u3059\r\nUPDATE APP100\r\nSET \u96FB\u8A71\u756A\u53F7 = REPLACE(REPLACE(\u96FB\u8A71\u756A\u53F7, '-', ''), ' ', '')\r\nWHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n```\r\n\r\n```sql\r\n-- \u9867\u5BA2\u30B3\u30FC\u30C9\u3092 8 \u6841\u30BC\u30ED\u57CB\u3081\u3078\uFF08\u5148\u982D\u30BC\u30ED\u306F\u6587\u5B57\u5217\u306E\u307E\u307E\u4FDD\u6301\u3055\u308C\u308B\uFF09\r\nUPDATE APP100 SET \u9867\u5BA2\u30B3\u30FC\u30C9 = LPAD(\u9867\u5BA2\u30B3\u30FC\u30C9, 8, '0') WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406');\r\n```\r\n\r\n- **\u89AA DML \u306E `WHERE` \u306B\u95A2\u6570\u306F\u66F8\u3051\u306A\u3044**\u305F\u3081\u3001\u5F62 A \u306F\u300C\u5909\u63DB\u304C\u4E0D\u8981\u306A\u884C\u300D\u3082\u542B\u3081\u3066 WHERE \u6761\u4EF6\u306E\u5168\u884C\u3078 PUT \u3057\u307E\u3059\u3002**\u5024\u306F\u51AA\u7B49\u3067\u3082\u526F\u4F5C\u7528\u306F\u51AA\u7B49\u3067\u306F\u3042\u308A\u307E\u305B\u3093** \u2014 \u540C\u5024\u3067\u3082\u66F4\u65B0\u6271\u3044\u306B\u306A\u308A\u3001\u66F4\u65B0\u65E5\u6642\u304C\u5909\u308F\u308A\u3001\u901A\u77E5\u30FBWebhook\u30FB\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA JS \u304C\u767A\u706B\u3057\u5F97\u307E\u3059\u3002\u30EA\u30E9\u30F3\u3084\u526F\u4F5C\u7528\u3092\u6291\u3048\u305F\u3044\u5834\u5408\u306F\u5F62 B \u304C\u5B89\u5168\u3067\u3059\u3002`VALIDATE ONLY` \u306F**\u691C\u8A3C\u30A8\u30E9\u30FC\u306E\u6709\u7121**\u3092\u66F8\u304D\u8FBC\u307F\u30BC\u30ED\u3067\u4E8B\u524D\u78BA\u8A8D\u3059\u308B\u3082\u306E\u3067\uFF08\u30A8\u30E9\u30FC\u884C\u3060\u3051\u304C\u8FD4\u308B\uFF09\u3001\u6B63\u5E38\u884C\u306E\u5909\u63DB\u5F8C\u306E\u5024\u4E00\u89A7\u3092\u30D7\u30EC\u30D3\u30E5\u30FC\u3059\u308B\u6A5F\u80FD\u3067\u306F\u3042\u308A\u307E\u305B\u3093\r\n- `UPDATE \u2026 FROM` \u3068\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306E `SET` \u306B\u306F\u95A2\u6570\u3092\u76F4\u63A5\u66F8\u3051\u307E\u305B\u3093\uFF08\u660E\u793A\u30A8\u30E9\u30FC\uFF09\r\n\r\n**\u5F62 B: \u5909\u63DB\u304C\u5FC5\u8981\u306A\u884C\u3060\u3051\u3078\u7D5E\u308B\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u7D4C\u7531\u30FB\u5F93\u6765\u306E\u5B9A\u77F3\uFF09**\r\n\r\n```sql\r\nCREATE TEMP TABLE #norm AS\r\n SELECT $id AS \u5BFE\u8C61id,\r\n REPLACE(REPLACE(\u96FB\u8A71\u756A\u53F7, '-', ''), ' ', '') AS \u6B63\u898F\u5316\r\n FROM APP100\r\n WHERE \u51E6\u7406\u30B9\u30C6\u30FC\u30BF\u30B9 IN ('\u672A\u51E6\u7406')\r\n AND LENGTH(\u96FB\u8A71\u756A\u53F7) > LENGTH(REPLACE(REPLACE(\u96FB\u8A71\u756A\u53F7, '-', ''), ' ', ''));\r\nUPDATE APP100 SET \u96FB\u8A71\u756A\u53F7 = n.\u6B63\u898F\u5316 FROM #norm AS n WHERE APP100.$id = n.\u5BFE\u8C61id;\r\n```\r\n\r\nSELECT \u5074\u306E `WHERE` \u306A\u3089\u95A2\u6570\u3067\u300C\u5909\u63DB\u3059\u308B\u3068\u5909\u308F\u308B\u884C\u300D\u3060\u3051\u3092\u9078\u3079\u307E\u3059\u3002\u5BFE\u8C61 0 \u4EF6\u3067\u3082 `UPDATE \u2026 FROM` \u306F no-op \u3067\u5B8C\u8D70\u3057\u307E\u3059\uFF08\u30EA\u30E9\u30F3\u5B89\u5168\uFF09\u3002\r\n\r\n---", uri: "ksql://recipes/r10" }, r11: { heading: "R11. \u30D5\u30A1\u30A4\u30EB\u304B\u3089\u30A2\u30D7\u30EA\u3078\u53D6\u8FBC\u3080\uFF08`IMPORT`\u30FBv3.6.0\uFF09", text: "## R11. \u30D5\u30A1\u30A4\u30EB\u304B\u3089\u30A2\u30D7\u30EA\u3078\u53D6\u8FBC\u3080\uFF08`IMPORT`\u30FBv3.6.0\uFF09\r\n\r\nCSV / JSON \u30D5\u30A1\u30A4\u30EB\u3092\u3001**\u5909\u63DB\u30FB\u691C\u8A3C\u30FB\u4E0D\u826F\u884C\u9694\u96E2\u4ED8\u304D\u3067**\u30A2\u30D7\u30EA\u3078\u53D6\u8FBC\u3080\u81EA\u5DF1\u5B8C\u7D50\u30B9\u30C6\u30FC\u30C8\u30E1\u30F3\u30C8\u3002\u30BD\u30FC\u30B9\u306F**\u9762\u304C\u540D\u524D\u4ED8\u304D\u3067\u4F9B\u7D66**\u3057\u3001SQL \u306B\u30D1\u30B9\u3092\u57CB\u3081\u307E\u305B\u3093\uFF08`IMPORT` \u306F source \u4F9B\u7D66\u6642\u306E\u307F\u6709\u52B9\uFF1Doff-by-default\uFF09\u3002\r\n\r\n| \u9762 | \u30BD\u30FC\u30B9\u4F9B\u7D66 |\r\n|---|---|\r\n| CLI | `--import-csv =` / `--import-json =` |\r\n| MCP | `importSources: [{ name, text \\| base64, encoding? }]`\uFF08inline\u30FB\u30D1\u30B9\u4E0D\u53EF\uFF09 |\r\n| \u30D7\u30E9\u30B0\u30A4\u30F3 | \u30D8\u30C3\u30C0\u30FC\u306E\u300C\u30D5\u30A1\u30A4\u30EB\u3092\u9078\u629E\u300D\uFF08\u30BD\u30FC\u30B9\u540D\uFF1D\u62E1\u5F35\u5B50\u3092\u9664\u53BB\u3057\u8B58\u5225\u5B50\u306B\u4F7F\u3048\u306A\u3044\u6587\u5B57\u3092 `_` \u306B\u6B63\u898F\u5316\u3002`sales.csv` \u2192 `sales`\u3001`sales 2026.csv` \u2192 `sales_2026`\uFF09 |\r\n\r\n**\u30D5\u30E9\u30C3\u30C8 CSV \u3092\u5C04\u5F71\u3057\u3066 UPSERT**\uFF08`CAST` \u3067\u6570\u5024\u5316\u30FB\u696D\u52D9\u30AD\u30FC\u3067\u91CD\u8907\u5224\u5B9A\uFF09:\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D)\r\nFROM CSV sales\r\nSELECT code, CAST(amount AS NUMBER) AS \u91D1\u984D\r\nON DUPLICATE (\u9867\u5BA2\u30B3\u30FC\u30C9);\r\n```\r\n\r\n**\u4E0D\u826F\u884C\u3092\u9694\u96E2\u3057\u3066\u6B8B\u308A\u3092\u6D41\u3059**\uFF08`ON ERROR SKIP`\u30FBR6 \u3068\u540C\u3058\u601D\u60F3\uFF09:\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D) FROM CSV sales BY NAME\r\nON ERROR SKIP INTO #err;\r\nSELECT * FROM #err;\r\n```\r\n\r\n**JSON**\uFF08\u53B3\u5BC610\u9032\u30FB\u7CBE\u5EA6\u5BFE\u8C61\u306E NUMBER \u306F string \u4F9B\u7D66\u30FB\u5168\u968E\u5C64 duplicate key \u62D2\u5426\uFF09:\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D) FROM JSON payload;\r\n```\r\n\r\n- `VALIDATE ONLY` \u3067**\u66F8\u8FBC\u307F\u524D\u306B\u5168\u884C\u691C\u8A3C**\uFF08`ksql_validate` \u306F\u69CB\u6587\u306E\u307F\u30FB\u5B9F\u884C\u53EF\u5426\u306F VALIDATE ONLY \u3067\u78BA\u8A8D\u3059\u308B\uFF09\u3002\r\n- `CHECK WHEN \u2026 THEN \u2026`\uFF08B37\uFF09\u3067\u884C\u30EC\u30D9\u30EB\u696D\u52D9\u30EB\u30FC\u30EB\u3092\u4ED8\u4E0E\u3067\u304D\u308B\u3002\r\n- **\u53D6\u8FBC\u884C\u6570\u306E\u4E0A\u9650 `maxRecords` \u306F\u9762\u30FB\u7D4C\u8DEF\u3067\u7570\u306A\u308B**\uFF08\u8D85\u904E\u306F fail-closed\u30FB\u30B5\u30A4\u30EC\u30F3\u30C8\u5207\u308A\u6368\u3066\u306A\u3057\uFF09: CLI=\u65E2\u5B9A **500**\uFF08`--max-records`\uFF09\uFF0F\u30D7\u30E9\u30B0\u30A4\u30F3=\u521D\u671F **3000**\uFF08UI \u53EF\u5909\uFF09\uFF0FMCP=\u901A\u5E38 mutation \u306F `dmlMaxRows`\uFF08\uFF0B1\uFF09\u3067\u89E3\u6C7A\u30FB`ON ERROR SKIP` / `VALIDATE ONLY` \u306F runtime `maxRecords` \u306B\u623B\u308B\u3002CSV \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u7F6E\u63DB\u3067\u306F\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u5168\u4EF6\u8D70\u67FB\u306B\u3082\u540C\u4E0A\u9650\u304C\u52B9\u304F\uFF08\u5F8C\u8FF0\uFF09\u3002", uri: "ksql://recipes/r11" }, r12: { heading: "R12. cli-kintone \u3068 round-trip \u3059\u308B\uFF08`BY NAME`\u30FB\u30EC\u30B3\u30FC\u30C9\u756A\u53F7 UPDATE\u30FB\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u30FBv3.6.0\uFF09", text: "## R12. cli-kintone \u3068 round-trip \u3059\u308B\uFF08`BY NAME`\u30FB\u30EC\u30B3\u30FC\u30C9\u756A\u53F7 UPDATE\u30FB\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u30FBv3.6.0\uFF09\r\n\r\nkintone \u516C\u5F0F CLI `cli-kintone` \u3067 export \u3057\u305F CSV \u3092\u3001\u305D\u306E\u307E\u307E kSQL \u3078\u623B\u305B\u307E\u3059\u3002\r\n\r\n**\u30D5\u30E9\u30C3\u30C8 export \u3092\u53D6\u8FBC\u3080**\uFF08\u30D8\u30C3\u30C0\uFF1D\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9\u540D\u3067\u5BFE\u5FDC\u30FB\u975E\u66F8\u8FBC\u307F\u5217\u306F\u76E3\u67FB\u4ED8\u304D\u7121\u8996\u30FB\u8907\u6570\u5024\u306F\u30BB\u30EB\u5185 LF\uFF09:\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u91D1\u984D, \u62C5\u5F53\u8005)\r\nFROM CSV exported BY NAME IGNORE UNKNOWN COLUMNS;\r\n```\r\n\r\n**\u30EC\u30B3\u30FC\u30C9\u756A\u53F7\u3092\u30AD\u30FC\u306B\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u3092\u66F4\u65B0**\uFF08\u7D14 UPDATE\u30FBINSERT 0\u30FB\u756A\u53F7\u306F\u7167\u5408\u5C02\u7528\uFF09:\r\n```sql\r\nIMPORT UPDATE INTO APP100 (\u91D1\u984D)\r\nFROM CSV exported BY NAME\r\nMATCH RECORD NUMBER SOURCE `\u30EC\u30B3\u30FC\u30C9\u756A\u53F7`;\r\n```\r\n\r\n**\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB**\uFF08\u610F\u5473\u8AD6\u304C source \u3067\u7570\u306A\u308B\uFF09:\r\n- **JSON**\uFF08\u30CD\u30B9\u30C8\u914D\u5217\u30FB**\u65B0\u898F INSERT / \u696D\u52D9\u30AD\u30FC UPSERT**\u30FB\u884C ID \u306A\u3057\u5168\u7F6E\u63DB\uFF09:\r\n```sql\r\nIMPORT INTO APP100 (\u9867\u5BA2\u30B3\u30FC\u30C9, \u660E\u7D30(\u54C1\u540D, \u6570\u91CF)) FROM JSON payload;\r\n```\r\n- **CSV `*` \u5F62\u5F0F**\uFF08cli-kintone export\u30FB**\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u306E UPDATE \u5168\u7F6E\u63DB**\u30FB\u884C ID \u7DAD\u6301\u66F4\u65B0/\u6B20\u843D\u524A\u9664\uFF09:\r\n```sql\r\nIMPORT UPDATE INTO APP100 (\u660E\u7D30(\u54C1\u540D, \u6570\u91CF) ROW ID SOURCE `\u660E\u7D30_\u884CID`)\r\nFROM CSV exported BY NAME\r\nMATCH RECORD NUMBER SOURCE `\u30EC\u30B3\u30FC\u30C9\u756A\u53F7`\r\nREPLACE SUBTABLES (\u660E\u7D30);\r\n```\r\n\r\n**cli-kintone \u3068\u306E\u4F7F\u3044\u5206\u3051**:\r\n\r\n| \u7528\u9014 | \u63A8\u5968 |\r\n|---|---|\r\n| \u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\u8FBC\u307F\u306E\u53D6\u8FBC\u30FB\u5358\u7D14\u306A\u4E00\u62EC\u30ED\u30FC\u30C9 | **cli-kintone** |\r\n| \u53D6\u8FBC\u6642\u306E\u5909\u63DB\uFF08`CAST`/\u95A2\u6570\uFF09\u30FB\u696D\u52D9\u30C1\u30A7\u30C3\u30AF\u30FB\u4E0D\u826F\u884C\u9694\u96E2\u30FBSQL \u30D1\u30A4\u30D7\u30E9\u30A4\u30F3\u7D71\u5408\u30FBMCP/\u30D6\u30E9\u30A6\u30B6\u304B\u3089 | **kSQL IMPORT** |\r\n\r\n- **\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\uFF08FILE\uFF09\u306F kSQL IMPORT \u975E\u5BFE\u5FDC**\uFF08cli-kintone \u3092\u4F7F\u3046\uFF09\u3002\r\n- **CSV \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306F UPDATE \u5C02\u7528**\uFF08`REPLACE SUBTABLES` \u3067\u5168\u7F6E\u63DB\uFF09\u3002**\u65B0\u898F INSERT \u306F JSON**\u3002\r\n- **\u7834\u58CA\u7684\u5168\u7F6E\u63DB\u306F\u9762\u304C\u524A\u9664\u5185\u8A33\u3092 confirm \u8868\u793A\u3067\u304D\u308B\u3068\u304D\u3060\u3051\u5B9F\u884C**\uFF08fail-closed\uFF09\uFF0B\u524A\u9664\u4EF6\u6570\u3092\u660E\u793A\u3002\u5168\u7F6E\u63DB\u306E\u6307\u5B9A\u306F\u30BD\u30FC\u30B9\u7A2E\u5225\u3067\u7570\u306A\u308B\uFF1D**CSV \u306F `REPLACE SUBTABLES` \u5FC5\u9808\uFF0FJSON \u306F\u30CD\u30B9\u30C8\u914D\u5217\u304C\u5168\u7F6E\u63DB\u5BFE\u8C61**\uFF08JSON UPSERT \u3082\u65E2\u5B58\u5B50\u884C\u3092\u524A\u9664\u3059\u308B\u304C `REPLACE SUBTABLES` \u306F\u66F8\u304B\u306A\u3044\u30FB\u66F8\u304F\u3068\u69CB\u6587\u30A8\u30E9\u30FC\uFF09\u3002\r\n- **MCP \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB mutation \u3092 fail-closed**\uFF08\u524A\u9664\u5185\u8A33\u3092\u5BFE\u8A71\u627F\u8A8D\u3067\u304D\u306A\u3044\u305F\u3081\uFF09\u2192 \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u66F8\u8FBC\u307F\u306F CLI / \u30D7\u30E9\u30B0\u30A4\u30F3\u3001MCP \u306F `ksql_query` \u306E `VALIDATE ONLY`\uFF0F`ksql_explain` \u306E `EXPLAIN` \u307E\u3067\u3002\r\n- **CSV \u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u7F6E\u63DB\u306E\u8D70\u67FB\u4E0A\u9650**: \u884C ID \u6240\u6709\u6A29\u691C\u67FB\u3067\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u3092\u5168\u4EF6\u8D70\u67FB\u3059\u308B\u305F\u3081\u3001\u53D6\u8FBC\u89AA\u304C\u5C11\u6570\u3067\u3082\u65E2\u5B58\u30EC\u30B3\u30FC\u30C9\u304C `maxRecords` \u3092\u8D85\u3048\u308B\u3068 fail-closed \u306B\u306A\u308B\u3002\r\n- \u6A19\u6E96\u30B9\u30DA\u30FC\u30B9\u30FB**\u30B2\u30B9\u30C8\u30B9\u30DA\u30FC\u30B9**\u306E\u4E21\u65B9\u3067\u52D5\u4F5C\u3059\u308B\u3002", uri: "ksql://recipes/r12" } } } }; } }); // node_modules/ajv/dist/compile/codegen/code.js var require_code = __commonJS({ "node_modules/ajv/dist/compile/codegen/code.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.regexpCode = exports2.getEsmExportName = exports2.getProperty = exports2.safeStringify = exports2.stringify = exports2.strConcat = exports2.addCodeArg = exports2.str = exports2._ = exports2.nil = exports2._Code = exports2.Name = exports2.IDENTIFIER = exports2._CodeOrName = void 0; var _CodeOrName = class { }; exports2._CodeOrName = _CodeOrName; exports2.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s) { super(); if (!exports2.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports2.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a3; return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); } get names() { var _a3; return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}); } }; exports2._Code = _Code; exports2.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports2._ = _; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports2.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports2.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== void 0) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports2.strConcat = strConcat; function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports2.stringify = stringify; function safeStringify(x) { return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports2.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports2.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; } exports2.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports2.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports2.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports2.regexpCode = regexpCode; } }); // node_modules/ajv/dist/compile/codegen/scope.js var require_scope = __commonJS({ "node_modules/ajv/dist/compile/codegen/scope.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0; var code_1 = require_code(); var ValueError = class extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports2.UsedValueState = UsedValueState = {})); exports2.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a3, _b; if (((_b = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports2.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports2.ValueScopeName = ValueScopeName; var line = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a3; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = /* @__PURE__ */ new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._)`${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const; code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } }; exports2.ValueScope = ValueScope; } }); // node_modules/ajv/dist/compile/codegen/index.js var require_codegen = __commonJS({ "node_modules/ajv/dist/compile/codegen/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0; var code_1 = require_code(); var scope_1 = require_scope(); var code_2 = require_code(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports2, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports2, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope(); Object.defineProperty(exports2, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports2, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports2.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } }; var Label = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } }; var Break = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } }; var Throw = class extends Node { constructor(error51) { super(); this.error = error51; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } }; var AnyCode = class extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class _If extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof _If ? e : e.nodes; if (this.nodes.length) return this; return new _If(not(cond), e instanceof _If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a3; this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a3, _b; super.optimizeNodes(); (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a3, _b; super.optimizeNames(names, constants); (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error51) { super(); this.error = error51; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports2.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { this.var(name, (0, code_1._)`${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error51 = this.name("e"); this._currNode = node.catch = new Catch(error51); catchCode(error51); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error51) { return this._leafNode(new Throw(error51)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || N2 && n instanceof N2) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } }; exports2.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === void 0 || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; } exports2.not = not; var andCode = mappend(exports2.operators.AND); function and(...args) { return args.reduce(andCode); } exports2.and = and; var orCode = mappend(exports2.operators.OR); function or(...args) { return args.reduce(orCode); } exports2.or = or; function mappend(op) { return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; } } }); // node_modules/ajv/dist/compile/util.js var require_util = __commonJS({ "node_modules/ajv/dist/compile/util.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0; var codegen_1 = require_codegen(); var code_1 = require_code(); function toHash(arr) { const hash2 = {}; for (const item of arr) hash2[item] = true; return hash2; } exports2.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports2.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports2.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports2.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports2.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports2.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports2.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports2.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports2.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports2.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports2.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports2.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps !== void 0) setEvaluated(gen, props, ps); return props; } exports2.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports2.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); } exports2.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports2.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber2 = dataPropType === Type.Num; return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports2.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports2.checkStrictMode = checkStrictMode; } }); // node_modules/ajv/dist/compile/names.js var require_names = __commonJS({ "node_modules/ajv/dist/compile/names.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports2.default = names; } }); // node_modules/ajv/dist/compile/errors.js var require_errors = __commonJS({ "node_modules/ajv/dist/compile/errors.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var names_1 = require_names(); exports2.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports2.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error51 = exports2.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error51, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._)`[${errObj}]`); } } exports2.reportError = reportError; function reportExtraError(cxt, error51 = exports2.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error51, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports2.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports2.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err}.data`, data); } }); } exports2.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error51, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error51, errorPaths); } function errorObject(cxt, error51, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error51, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } } }); // node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema = __commonJS({ "node_modules/ajv/dist/compile/validate/boolSchema.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.boolOrEmptySchema = exports2.topBoolOrEmptySchema = void 0; var errors_1 = require_errors(); var codegen_1 = require_codegen(); var names_1 = require_names(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports2.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); falseSchemaError(it); } else { gen.var(valid, true); } } exports2.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/ajv/dist/compile/rules.js var require_rules = __commonJS({ "node_modules/ajv/dist/compile/rules.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getRules = exports2.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports2.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports2.getRules = getRules; } }); // node_modules/ajv/dist/compile/validate/applicability.js var require_applicability = __commonJS({ "node_modules/ajv/dist/compile/validate/applicability.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.shouldUseRule = exports2.shouldUseGroup = exports2.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports2.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports2.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a3; return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0)); } exports2.shouldUseRule = shouldUseRule; } }); // node_modules/ajv/dist/compile/validate/dataType.js var require_dataType = __commonJS({ "node_modules/ajv/dist/compile/validate/dataType.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.reportTypeError = exports2.checkDataTypes = exports2.checkDataType = exports2.coerceAndCheckDataType = exports2.getJSONTypes = exports2.getSchemaTypes = exports2.DataType = void 0; var rules_1 = require_rules(); var applicability_1 = require_applicability(); var errors_1 = require_errors(); var codegen_1 = require_codegen(); var util_1 = require_util(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports2.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports2.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports2.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports2.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports2.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports2.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports2.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it }; } } }); // node_modules/ajv/dist/compile/validate/defaults.js var require_defaults = __commonJS({ "node_modules/ajv/dist/compile/validate/defaults.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.assignDefaults = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports2.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/ajv/dist/vocabularies/code.js var require_code2 = __commonJS({ "node_modules/ajv/dist/vocabularies/code.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var names_1 = require_names(); var util_2 = require_util(); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports2.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports2.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports2.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports2.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports2.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports2.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports2.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports2.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports2.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports2.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); } exports2.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports2.validateArray = validateArray; function validateUnion2(cxt) { const { gen, schema, keyword, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports2.validateUnion = validateUnion2; } }); // node_modules/ajv/dist/compile/validate/keyword.js var require_keyword = __commonJS({ "node_modules/ajv/dist/compile/validate/keyword.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateKeywordUsage = exports2.validSchemaType = exports2.funcKeywordCode = exports2.macroKeywordCode = void 0; var codegen_1 = require_codegen(); var names_1 = require_names(); var code_1 = require_code2(); var errors_1 = require_errors(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports2.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a3; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a4; gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors); } } exports2.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); } exports2.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports2.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/ajv/dist/compile/validate/subschema.js var require_subschema = __commonJS({ "node_modules/ajv/dist/compile/validate/subschema.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.extendSubschemaMode = exports2.extendSubschemaData = exports2.getSubschema = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports2.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports2.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports2.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/fast-deep-equal/index.js var require_fast_deep_equal = __commonJS({ "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); module2.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == "object" && typeof b == "object") { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0; ) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0; ) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } return a !== a && b !== b; }; } }); // node_modules/json-schema-traverse/index.js var require_json_schema_traverse = __commonJS({ "node_modules/json-schema-traverse/index.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); var traverse = module2.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/ajv/dist/compile/resolve.js var require_resolve = __commonJS({ "node_modules/ajv/dist/compile/resolve.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0; var util_1 = require_util(); var equal = require_fast_deep_equal(); var traverse = require_json_schema_traverse(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports2.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports2.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports2._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports2.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports2.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports2.getSchemaRefs = getSchemaRefs; } }); // node_modules/ajv/dist/compile/validate/index.js var require_validate = __commonJS({ "node_modules/ajv/dist/compile/validate/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getData = exports2.KeywordCxt = exports2.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema(); var dataType_1 = require_dataType(); var applicability_1 = require_applicability(); var dataType_2 = require_dataType(); var defaults_1 = require_defaults(); var keyword_1 = require_keyword(); var subschema_1 = require_subschema(); var codegen_1 = require_codegen(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util(); var errors_1 = require_errors(); function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports2.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults } } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts, t) { return ts.includes(t) || t === "integer" && ts.includes("number"); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } var KeywordCxt = class { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports2.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment of segments) { if (segment) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports2.getData = getData; } }); // node_modules/ajv/dist/runtime/validation_error.js var require_validation_error = __commonJS({ "node_modules/ajv/dist/runtime/validation_error.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports2.default = ValidationError; } }); // node_modules/ajv/dist/compile/ref_error.js var require_ref_error = __commonJS({ "node_modules/ajv/dist/compile/ref_error.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var resolve_1 = require_resolve(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports2.default = MissingRefError; } }); // node_modules/ajv/dist/compile/index.js var require_compile = __commonJS({ "node_modules/ajv/dist/compile/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0; var codegen_1 = require_codegen(); var validation_error_1 = require_validation_error(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { constructor(env) { var _a3; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports2.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e; } finally { this._compilations.delete(sch); } } exports2.compileSchema = compileSchema; function resolveRef2(root, baseId, ref) { var _a3; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve3.call(this, root, ref); if (_sch === void 0) { const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports2.resolveRef = resolveRef2; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports2.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve3(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports2.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a3; if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/ajv/dist/refs/data.json var require_data = __commonJS({ "node_modules/ajv/dist/refs/data.json"(exports2, module2) { module2.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/fast-uri/lib/utils.js var require_utils = __commonJS({ "node_modules/fast-uri/lib/utils.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu); var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu); var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu); function stringArrayToHexStripped(input) { let acc = ""; let code = 0; let i = 0; for (i = 0; i < input.length; i++) { code = input[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } acc += input[i]; break; } for (i += 1; i < input.length; i++) { code = input[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } acc += input[i]; } return acc; } var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); function consumeIsZone(buffer) { buffer.length = 0; return true; } function consumeHextets(buffer, address, output) { if (buffer.length) { const hex3 = stringArrayToHexStripped(buffer); if (hex3 !== "") { address.push(hex3); } else { output.error = true; return false; } buffer.length = 0; } return true; } function getIPV6(input) { let tokenCount = 0; const output = { error: false, address: "", zone: "" }; const address = []; const buffer = []; let endipv6Encountered = false; let endIpv6 = false; let consume = consumeHextets; for (let i = 0; i < input.length; i++) { const cursor = input[i]; if (cursor === "[" || cursor === "]") { continue; } if (cursor === ":") { if (endipv6Encountered === true) { endIpv6 = true; } if (!consume(buffer, address, output)) { break; } if (++tokenCount > 7) { output.error = true; break; } if (i > 0 && input[i - 1] === ":") { endipv6Encountered = true; } address.push(":"); continue; } else if (cursor === "%") { if (!consume(buffer, address, output)) { break; } consume = consumeIsZone; } else { buffer.push(cursor); continue; } } if (buffer.length) { if (consume === consumeIsZone) { output.zone = buffer.join(""); } else if (endIpv6) { address.push(buffer.join("")); } else { address.push(stringArrayToHexStripped(buffer)); } } output.address = address.join(""); return output; } function normalizeIPv6(host) { if (findToken(host, ":") < 2) { return { host, isIPV6: false }; } const ipv63 = getIPV6(host); if (!ipv63.error) { let newHost = ipv63.address; let escapedHost = ipv63.address; if (ipv63.zone) { newHost += "%" + ipv63.zone; escapedHost += "%25" + ipv63.zone; } return { host: newHost, isIPV6: true, escapedHost }; } else { return { host, isIPV6: false }; } } function findToken(str, token) { let ind = 0; for (let i = 0; i < str.length; i++) { if (str[i] === token) ind++; } return ind; } function removeDotSegments(path) { let input = path; const output = []; let nextSlash = -1; let len = 0; while (len = input.length) { if (len === 1) { if (input === ".") { break; } else if (input === "/") { output.push("/"); break; } else { output.push(input); break; } } else if (len === 2) { if (input[0] === ".") { if (input[1] === ".") { break; } else if (input[1] === "/") { input = input.slice(2); continue; } } else if (input[0] === "/") { if (input[1] === "." || input[1] === "/") { output.push("/"); break; } } } else if (len === 3) { if (input === "/..") { if (output.length !== 0) { output.pop(); } output.push("/"); break; } } if (input[0] === ".") { if (input[1] === ".") { if (input[2] === "/") { input = input.slice(3); continue; } } else if (input[1] === "/") { input = input.slice(2); continue; } } else if (input[0] === "/") { if (input[1] === ".") { if (input[2] === "/") { input = input.slice(2); continue; } else if (input[2] === ".") { if (input[3] === "/") { input = input.slice(3); if (output.length !== 0) { output.pop(); } continue; } } } } if ((nextSlash = input.indexOf("/", 1)) === -1) { output.push(input); break; } else { output.push(input.slice(0, nextSlash)); input = input.slice(nextSlash); } } return output.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; var HOST_DELIM_NO_COLON_RE = /[@/?#]/g; function reescapeHostDelimiters(host, isIP) { const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE; re.lastIndex = 0; return host.replace(re, (ch) => HOST_DELIMS[ch]); } function normalizePercentEncoding(input, decodeUnreserved = false) { if (input.indexOf("%") === -1) { return input; } let output = ""; for (let i = 0; i < input.length; i++) { if (input[i] === "%" && i + 2 < input.length) { const hex3 = input.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { output += decoded; } else { output += "%" + normalizedHex; } i += 2; continue; } } output += input[i]; } return output; } function normalizePathEncoding(input) { let output = ""; for (let i = 0; i < input.length; i++) { if (input[i] === "%" && i + 2 < input.length) { const hex3 = input.slice(i + 1, i + 3); if (isHexPair(hex3)) { const normalizedHex = hex3.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { output += decoded; } else { output += "%" + normalizedHex; } i += 2; continue; } } if (isPathCharacter(input[i])) { output += input[i]; } else { output += escape(input[i]); } } return output; } function escapePreservingEscapes(input) { let output = ""; for (let i = 0; i < input.length; i++) { if (input[i] === "%" && i + 2 < input.length) { const hex3 = input.slice(i + 1, i + 3); if (isHexPair(hex3)) { output += "%" + hex3.toUpperCase(); i += 2; continue; } } output += escape(input[i]); } return output; } function recomposeAuthority(component) { const uriTokens = []; if (component.userinfo !== void 0) { uriTokens.push(component.userinfo); uriTokens.push("@"); } if (component.host !== void 0) { let host = unescape(component.host); if (!isIPv4(host)) { const ipV6res = normalizeIPv6(host); if (ipV6res.isIPV6 === true) { host = `[${ipV6res.escapedHost}]`; } else { host = reescapeHostDelimiters(host, false); } } uriTokens.push(host); } if (typeof component.port === "number" || typeof component.port === "string") { uriTokens.push(":"); uriTokens.push(String(component.port)); } return uriTokens.length ? uriTokens.join("") : void 0; } module2.exports = { nonSimpleDomain, recomposeAuthority, reescapeHostDelimiters, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, removeDotSegments, isIPv4, isUUID, normalizeIPv6, stringArrayToHexStripped }; } }); // node_modules/fast-uri/lib/schemes.js var require_schemes = __commonJS({ "node_modules/fast-uri/lib/schemes.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); var { isUUID } = require_utils(); var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; var supportedSchemeNames = ( /** @type {const} */ [ "http", "https", "ws", "wss", "urn", "urn:uuid" ] ); function isValidSchemeName(name) { return supportedSchemeNames.indexOf( /** @type {*} */ name ) !== -1; } function wsIsSecure(wsComponent) { if (wsComponent.secure === true) { return true; } else if (wsComponent.secure === false) { return false; } else if (wsComponent.scheme) { return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); } else { return false; } } function httpParse(component) { if (!component.host) { component.error = component.error || "HTTP URIs must have a host."; } return component; } function httpSerialize(component) { const secure = String(component.scheme).toLowerCase() === "https"; if (component.port === (secure ? 443 : 80) || component.port === "") { component.port = void 0; } if (!component.path) { component.path = "/"; } return component; } function wsParse(wsComponent) { wsComponent.secure = wsIsSecure(wsComponent); wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); wsComponent.path = void 0; wsComponent.query = void 0; return wsComponent; } function wsSerialize(wsComponent) { if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { wsComponent.port = void 0; } if (typeof wsComponent.secure === "boolean") { wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; wsComponent.secure = void 0; } if (wsComponent.resourceName) { const [path, query] = wsComponent.resourceName.split("?"); wsComponent.path = path && path !== "/" ? path : void 0; wsComponent.query = query; wsComponent.resourceName = void 0; } wsComponent.fragment = void 0; return wsComponent; } function urnParse(urnComponent, options) { if (!urnComponent.path) { urnComponent.error = "URN can not be parsed"; return urnComponent; } const matches = urnComponent.path.match(URN_REG); if (matches) { const scheme = options.scheme || urnComponent.scheme || "urn"; urnComponent.nid = matches[1].toLowerCase(); urnComponent.nss = matches[2]; const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; const schemeHandler = getSchemeHandler(urnScheme); urnComponent.path = void 0; if (schemeHandler) { urnComponent = schemeHandler.parse(urnComponent, options); } } else { urnComponent.error = urnComponent.error || "URN can not be parsed."; } return urnComponent; } function urnSerialize(urnComponent, options) { if (urnComponent.nid === void 0) { throw new Error("URN without nid cannot be serialized"); } const scheme = options.scheme || urnComponent.scheme || "urn"; const nid = urnComponent.nid.toLowerCase(); const urnScheme = `${scheme}:${options.nid || nid}`; const schemeHandler = getSchemeHandler(urnScheme); if (schemeHandler) { urnComponent = schemeHandler.serialize(urnComponent, options); } const uriComponent = urnComponent; const nss = urnComponent.nss; uriComponent.path = `${nid || options.nid}:${nss}`; options.skipEscape = true; return uriComponent; } function urnuuidParse(urnComponent, options) { const uuidComponent = urnComponent; uuidComponent.uuid = uuidComponent.nss; uuidComponent.nss = void 0; if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { uuidComponent.error = uuidComponent.error || "UUID is not valid."; } return uuidComponent; } function urnuuidSerialize(uuidComponent) { const urnComponent = uuidComponent; urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); return urnComponent; } var http = ( /** @type {SchemeHandler} */ { scheme: "http", domainHost: true, parse: httpParse, serialize: httpSerialize } ); var https = ( /** @type {SchemeHandler} */ { scheme: "https", domainHost: http.domainHost, parse: httpParse, serialize: httpSerialize } ); var ws = ( /** @type {SchemeHandler} */ { scheme: "ws", domainHost: true, parse: wsParse, serialize: wsSerialize } ); var wss = ( /** @type {SchemeHandler} */ { scheme: "wss", domainHost: ws.domainHost, parse: ws.parse, serialize: ws.serialize } ); var urn = ( /** @type {SchemeHandler} */ { scheme: "urn", parse: urnParse, serialize: urnSerialize, skipNormalize: true } ); var urnuuid = ( /** @type {SchemeHandler} */ { scheme: "urn:uuid", parse: urnuuidParse, serialize: urnuuidSerialize, skipNormalize: true } ); var SCHEMES = ( /** @type {Record} */ { http, https, ws, wss, urn, "urn:uuid": urnuuid } ); Object.setPrototypeOf(SCHEMES, null); function getSchemeHandler(scheme) { return scheme && (SCHEMES[ /** @type {SchemeName} */ scheme ] || SCHEMES[ /** @type {SchemeName} */ scheme.toLowerCase() ]) || void 0; } module2.exports = { wsIsSecure, SCHEMES, isValidSchemeName, getSchemeHandler }; } }); // node_modules/fast-uri/index.js var require_fast_uri = __commonJS({ "node_modules/fast-uri/index.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils(); var { SCHEMES, getSchemeHandler } = require_schemes(); function normalize(uri, options) { if (typeof uri === "string") { uri = /** @type {T} */ normalizeString(uri, options); } else if (typeof uri === "object") { uri = /** @type {T} */ parse3(serialize(uri, options), options); } return uri; } function resolve3(baseURI, relativeURI, options) { const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); schemelessOptions.skipEscape = true; return serialize(resolved, schemelessOptions); } function resolveComponent(base, relative, options, skipNormalization) { const target = {}; if (!skipNormalization) { base = parse3(serialize(base, options), options); relative = parse3(serialize(relative, options), options); } options = options || {}; if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (!relative.path) { target.path = base.path; if (relative.query !== void 0) { target.query = relative.query; } else { target.query = base.query; } } else { if (relative.path[0] === "/") { target.path = removeDotSegments(relative.path); } else { if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { target.path = "/" + relative.path; } else if (!base.path) { target.path = relative.path; } else { target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; } target.path = removeDotSegments(target.path); } target.query = relative.query; } target.userinfo = base.userinfo; target.host = base.host; target.port = base.port; } target.scheme = base.scheme; } target.fragment = relative.fragment; return target; } function equal(uriA, uriB, options) { const normalizedA = normalizeComparableURI(uriA, options); const normalizedB = normalizeComparableURI(uriB, options); return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase(); } function serialize(cmpts, opts) { const component = { host: cmpts.host, scheme: cmpts.scheme, userinfo: cmpts.userinfo, port: cmpts.port, path: cmpts.path, query: cmpts.query, nid: cmpts.nid, nss: cmpts.nss, uuid: cmpts.uuid, fragment: cmpts.fragment, reference: cmpts.reference, resourceName: cmpts.resourceName, secure: cmpts.secure, error: "" }; const options = Object.assign({}, opts); const uriTokens = []; const schemeHandler = getSchemeHandler(options.scheme || component.scheme); if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); if (component.path !== void 0) { if (!options.skipEscape) { component.path = escapePreservingEscapes(component.path); if (component.scheme !== void 0) { component.path = component.path.split("%3A").join(":"); } } else { component.path = normalizePercentEncoding(component.path); } } if (options.reference !== "suffix" && component.scheme) { uriTokens.push(component.scheme, ":"); } const authority = recomposeAuthority(component); if (authority !== void 0) { if (options.reference !== "suffix") { uriTokens.push("//"); } uriTokens.push(authority); if (component.path && component.path[0] !== "/") { uriTokens.push("/"); } } if (component.path !== void 0) { let s = component.path; if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s = removeDotSegments(s); } if (authority === void 0 && s[0] === "/" && s[1] === "/") { s = "/%2F" + s.slice(2); } uriTokens.push(s); } if (component.query !== void 0) { uriTokens.push("?", component.query); } if (component.fragment !== void 0) { uriTokens.push("#", component.fragment); } return uriTokens.join(""); } var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; function getParseError(parsed, matches) { if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") { return 'URI path must start with "/" when authority is present.'; } if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) { return "URI port is malformed."; } return void 0; } function parseWithStatus(uri, opts) { const options = Object.assign({}, opts); const parsed = { scheme: void 0, userinfo: void 0, host: "", port: void 0, path: "", query: void 0, fragment: void 0 }; let malformedAuthorityOrPort = false; let isIP = false; if (options.reference === "suffix") { if (options.scheme) { uri = options.scheme + ":" + uri; } else { uri = "//" + uri; } } const matches = uri.match(URI_PARSE); if (matches) { parsed.scheme = matches[1]; parsed.userinfo = matches[3]; parsed.host = matches[4]; parsed.port = parseInt(matches[5], 10); parsed.path = matches[6] || ""; parsed.query = matches[7]; parsed.fragment = matches[8]; if (isNaN(parsed.port)) { parsed.port = matches[5]; } const parseError = getParseError(parsed, matches); if (parseError !== void 0) { parsed.error = parsed.error || parseError; malformedAuthorityOrPort = true; } if (parsed.host) { const ipv4result = isIPv4(parsed.host); if (ipv4result === false) { const ipv6result = normalizeIPv6(parsed.host); parsed.host = ipv6result.host.toLowerCase(); isIP = ipv6result.isIPV6; } else { isIP = true; } } if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { parsed.reference = "same-document"; } else if (parsed.scheme === void 0) { parsed.reference = "relative"; } else if (parsed.fragment === void 0) { parsed.reference = "absolute"; } else { parsed.reference = "uri"; } if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; } const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { try { parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); } catch (e) { parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; } } } if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { if (uri.indexOf("%") !== -1) { if (parsed.scheme !== void 0) { parsed.scheme = unescape(parsed.scheme); } if (parsed.host !== void 0) { parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP); } } if (parsed.path) { parsed.path = normalizePathEncoding(parsed.path); } if (parsed.fragment) { try { parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); } catch { parsed.error = parsed.error || "URI malformed"; } } } if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(parsed, options); } } else { parsed.error = parsed.error || "URI can not be parsed."; } return { parsed, malformedAuthorityOrPort }; } function parse3(uri, opts) { return parseWithStatus(uri, opts).parsed; } function normalizeString(uri, opts) { return normalizeStringWithStatus(uri, opts).normalized; } function normalizeStringWithStatus(uri, opts) { const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts); return { normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts), malformedAuthorityOrPort }; } function normalizeComparableURI(uri, opts) { if (typeof uri === "string") { const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts); return malformedAuthorityOrPort ? void 0 : normalized; } if (typeof uri === "object") { return serialize(uri, opts); } } var fastUri = { SCHEMES, normalize, resolve: resolve3, resolveComponent, equal, serialize, parse: parse3 }; module2.exports = fastUri; module2.exports.default = fastUri; module2.exports.fastUri = fastUri; } }); // node_modules/ajv/dist/runtime/uri.js var require_uri = __commonJS({ "node_modules/ajv/dist/runtime/uri.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var uri = require_fast_uri(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports2.default = uri; } }); // node_modules/ajv/dist/core.js var require_core = __commonJS({ "node_modules/ajv/dist/core.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0; var validate_1 = require_validate(); Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); var ref_error_1 = require_ref_error(); var rules_1 = require_rules(); var compile_1 = require_compile(); var codegen_2 = require_codegen(); var resolve_1 = require_resolve(); var dataType_1 = require_dataType(); var util_1 = require_util(); var $dataRefSchema = require_data(); var uri_1 = require_uri(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o) { var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv2 = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = {}; this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta: meta3, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta3 && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta: meta3, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; } validate(schemaKeyRef, data) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta3) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta3); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta3); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv2.ValidationError = validation_error_1.default; Ajv2.MissingRefError = ref_error_1.default; exports2.default = Ajv2; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a3; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/ajv/dist/vocabularies/core/id.js var require_id = __commonJS({ "node_modules/ajv/dist/vocabularies/core/id.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/core/ref.js var require_ref = __commonJS({ "node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callRef = exports2.getValidate = void 0; var ref_error_1 = require_ref_error(); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var compile_1 = require_compile(); var util_1 = require_util(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports2.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a3; if (!it.opts.unevaluated) return; const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated; if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports2.callRef = callRef; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/core/index.js var require_core2 = __commonJS({ "node_modules/ajv/dist/vocabularies/core/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var id_1 = require_id(); var ref_1 = require_ref(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports2.default = core; } }); // node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error51 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error: error51, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error51 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error: error51, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports2.default = def; } }); // node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length = __commonJS({ "node_modules/ajv/dist/runtime/ucs2length.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports2.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); var error51 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error: error51, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); var error51 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error: error51, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; if ($data) { const { regExp } = it.opts.code; const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); const valid = gen.let("valid"); gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); cxt.fail$data((0, codegen_1._)`!${valid}`); } else { const regExp = (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error51 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error: error51, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/required.js var require_required = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); var error51 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error: error51, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error51 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error: error51, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/ajv/dist/runtime/equal.js var require_equal = __commonJS({ "node_modules/ajv/dist/runtime/equal.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var equal = require_fast_deep_equal(); equal.code = 'require("ajv/dist/runtime/equal").default'; exports2.default = equal; } }); // node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var dataType_1 = require_dataType(); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error51 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error: error51, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._)`${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/const.js var require_const = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error51 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error: error51, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error51 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error: error51, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/index.js var require_validation = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber(); var multipleOf_1 = require_multipleOf(); var limitLength_1 = require_limitLength(); var pattern_1 = require_pattern(); var limitProperties_1 = require_limitProperties(); var required_1 = require_required(); var limitItems_1 = require_limitItems(); var uniqueItems_1 = require_uniqueItems(); var const_1 = require_const(); var enum_1 = require_enum(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports2.default = validation; } }); // node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var error51 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error: error51, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports2.validateAdditionalItems = validateAdditionalItems; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/items.js var require_items = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/items.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateTuple = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports2.validateTuple = validateTuple; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var items_1 = require_items(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items2020 = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); var error51 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error: error51, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error51 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error: error51, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === void 0 ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max }); if (max === void 0 && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== void 0 && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); exports2.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports2.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports2.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports2.validateSchemaDeps = validateSchemaDeps; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error51 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error: error51, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); var error51 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error: error51, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var validate_1 = require_validate(); var code_1 = require_code2(); var util_1 = require_util(); var additionalProperties_1 = require_additionalProperties(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); var util_2 = require_util(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/not.js var require_not = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/not.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error51 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error: error51, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true }, schValid); } if (i > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/if.js var require_if = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error51 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error: error51, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); } exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems(); var prefixItems_1 = require_prefixItems(); var items_1 = require_items(); var items2020_1 = require_items2020(); var contains_1 = require_contains(); var dependencies_1 = require_dependencies(); var propertyNames_1 = require_propertyNames(); var additionalProperties_1 = require_additionalProperties(); var properties_1 = require_properties(); var patternProperties_1 = require_patternProperties(); var not_1 = require_not(); var anyOf_1 = require_anyOf(); var oneOf_1 = require_oneOf(); var allOf_1 = require_allOf(); var if_1 = require_if(); var thenElse_1 = require_thenElse(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports2.default = getApplicator; } }); // node_modules/ajv/dist/vocabularies/format/format.js var require_format = __commonJS({ "node_modules/ajv/dist/vocabularies/format/format.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error51 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error: error51, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports2.default = def; } }); // node_modules/ajv/dist/vocabularies/format/index.js var require_format2 = __commonJS({ "node_modules/ajv/dist/vocabularies/format/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var format_1 = require_format(); var format = [format_1.default]; exports2.default = format; } }); // node_modules/ajv/dist/vocabularies/metadata.js var require_metadata = __commonJS({ "node_modules/ajv/dist/vocabularies/metadata.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.contentVocabulary = exports2.metadataVocabulary = void 0; exports2.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports2.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/ajv/dist/vocabularies/draft7.js var require_draft7 = __commonJS({ "node_modules/ajv/dist/vocabularies/draft7.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var core_1 = require_core2(); var validation_1 = require_validation(); var applicator_1 = require_applicator(); var format_1 = require_format2(); var metadata_1 = require_metadata(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports2.default = draft7Vocabularies; } }); // node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types = __commonJS({ "node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports2.DiscrError = DiscrError = {})); } }); // node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator = __commonJS({ "node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var types_1 = require_types(); var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); var error51 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error: error51, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a3; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required: required2 }) { return Array.isArray(required2) && required2.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } } }; exports2.default = def; } }); // node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_07 = __commonJS({ "node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports2, module2) { module2.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/ajv/dist/ajv.js var require_ajv = __commonJS({ "node_modules/ajv/dist/ajv.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0; var core_1 = require_core(); var draft7_1 = require_draft7(); var discriminator_1 = require_discriminator(); var draft7MetaSchema = require_json_schema_draft_07(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv2 = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports2.Ajv = Ajv2; module2.exports = exports2 = Ajv2; module2.exports.Ajv = Ajv2; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = Ajv2; var validate_1 = require_validate(); Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error(); Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/ajv-formats/dist/formats.js var require_formats = __commonJS({ "node_modules/ajv-formats/dist/formats.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.formatNames = exports2.fastFormats = exports2.fullFormats = void 0; function fmtDef(validate, compare) { return { validate, compare }; } exports2.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date5, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true }; exports2.fastFormats = { ...exports2.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i }; exports2.formatNames = Object.keys(exports2.fullFormats); function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date5(str) { const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); } function compareDate(d1, d2) { if (!(d1 && d2)) return void 0; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; function getTime(strictTimeZone) { return function time3(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tz = matches[4]; const tzSign = matches[5] === "-" ? -1 : 1; const tzH = +(matches[6] || 0); const tzM = +(matches[7] || 0); if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; if (hr <= 23 && min <= 59 && sec < 60) return true; const utcMin = min - tzM * tzSign; const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; }; } function compareTime(s1, s2) { if (!(s1 && s2)) return void 0; const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); if (!(t1 && t2)) return void 0; return t1 - t2; } function compareIsoTime(t1, t2) { if (!(t1 && t2)) return void 0; const a1 = TIME.exec(t1); const a2 = TIME.exec(t2); if (!(a1 && a2)) return void 0; t1 = a1[1] + a1[2] + a1[3]; t2 = a2[1] + a2[2] + a2[3]; if (t1 > t2) return 1; if (t1 < t2) return -1; return 0; } var DATE_TIME_SEPARATOR = /t|\s/i; function getDateTime(strictTimeZone) { const time3 = getTime(strictTimeZone); return function date_time(str) { const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]); }; } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const d1 = new Date(dt1).valueOf(); const d2 = new Date(dt2).valueOf(); if (!(d1 && d2)) return void 0; return d1 - d2; } function compareIsoDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === void 0) return void 0; return res || compareTime(t1, t2); } var NOT_URI_FRAGMENT = /\/|:/; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } var MIN_INT32 = -(2 ** 31); var MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { return Number.isInteger(value); } function validateNumber() { return true; } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e) { return false; } } } }); // node_modules/ajv-formats/dist/limit.js var require_limit = __commonJS({ "node_modules/ajv-formats/dist/limit.js"(exports2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); exports2.formatLimitDefinition = void 0; var ajv_1 = require_ajv(); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error51 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; exports2.formatLimitDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error: error51, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self } = it; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 }); cxt.fail$data(compareCode(fmt)); } function compareCode(fmt) { return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"] }; var formatLimitPlugin = (ajv) => { ajv.addKeyword(exports2.formatLimitDefinition); return ajv; }; exports2.default = formatLimitPlugin; } }); // node_modules/ajv-formats/dist/index.js var require_dist = __commonJS({ "node_modules/ajv-formats/dist/index.js"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); Object.defineProperty(exports2, "__esModule", { value: true }); var formats_1 = require_formats(); var limit_1 = require_limit(); var codegen_1 = require_codegen(); var fullName = new codegen_1.Name("fullFormats"); var fastName = new codegen_1.Name("fastFormats"); var formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) (0, limit_1.default)(ajv); return ajv; }; formatsPlugin.get = (name, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f = formats[name]; if (!f) throw new Error(`Unknown format "${name}"`); return f; }; function addFormats(ajv, list, fs, exportName) { var _a3; var _b; (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) ajv.addFormat(f, fs[f]); } module2.exports = exports2 = formatsPlugin; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = formatsPlugin; } }); // src/mcp/docsResourceBuilder.cjs var require_docsResourceBuilder = __commonJS({ "src/mcp/docsResourceBuilder.cjs"(exports2, module2) { "use strict"; init_define_KSQL_DOCS(); var LANGUAGE_SLUGS = Object.freeze([ "basic-rules", "select", "arithmetic-expressions", "case-when", "string-number-functions", "where", "join", "group-by-aggregates", "having", "order-by", "limit-offset", "union", "with-cte", "show-apps-describe", "insert", "update", "upsert", "delete", "subtable-virtual-table", "reorder", "subqueries", "limitations", "ui-features", "explain", "batch-temp-tables", "assert" ]); function fail3(message) { throw new Error(`DocsResourceBuildError: ${message}`); } function documentTitle(source, label) { const match = /^#\s+(.+)$/m.exec(source); if (!match) fail3(`${label}: H1 title is missing`); return match[1].trim(); } function allH2Offsets(source) { const offsets = []; const regex = /^##\s+.+$/gm; for (let match = regex.exec(source); match; match = regex.exec(source)) { offsets.push(match.index); } return offsets; } function nextBoundary(source, start, shouldIgnoreHeading) { const regex = /^##\s+(.+)$/gm; regex.lastIndex = start; for (let match = regex.exec(source); match; match = regex.exec(source)) { if (!shouldIgnoreHeading(match[1])) return match.index; } return source.length; } function parseRequiredSections(source, options) { const { label, count, headingPattern, keyFor, uriBase, ignoreBoundary } = options; if (typeof source !== "string" || source.trim() === "") fail3(`${label}: document is empty`); if (allH2Offsets(source).length === 0) fail3(`${label}: H2 parse failed`); const found = /* @__PURE__ */ new Map(); const keys = /* @__PURE__ */ new Set(); for (let match = headingPattern.exec(source); match; match = headingPattern.exec(source)) { const number4 = Number(match[1]); const key = keyFor(number4, match[2]); if (keys.has(key)) fail3(`${label}: duplicate section key ${key}`); if (found.has(number4)) fail3(`${label}: duplicate chapter ${match[1]}`); const headingEnd = source.indexOf("\n", match.index); const contentStart = headingEnd < 0 ? source.length : headingEnd + 1; const end = nextBoundary(source, contentStart, ignoreBoundary); const body = source.slice(contentStart, end).trim(); if (body === "") fail3(`${label}: section ${key} is empty`); found.set(number4, { key, heading: match[0].replace(/^##\s+/, "").trim(), text: source.slice(match.index, end).trimEnd(), uri: `${uriBase}/${key}` }); keys.add(key); } if (found.size === 0) fail3(`${label}: required H2 sections could not be parsed`); const missing = []; for (let number4 = 1; number4 <= count; number4++) { if (!found.has(number4)) missing.push(number4); } if (missing.length > 0) fail3(`${label}: missing required chapters: ${missing.join(", ")}`); const sections = {}; for (let number4 = 1; number4 <= count; number4++) { const section = found.get(number4); sections[section.key] = { heading: section.heading, text: section.text, uri: section.uri }; } return sections; } function buildIndex(title, sourcePath, uri, summary, sections, overview = "") { const lines = [ `# ${title} index`, "", summary, "", `Source: \`${sourcePath}\``, "" ]; if (overview) lines.push(overview, ""); lines.push("## Sections", ""); for (const section of Object.values(sections)) { lines.push(`- [${section.heading}](${section.uri})`); } lines.push("", `Index URI: ${uri}`); return lines.join("\n"); } function extractH2Section(source, headingText, label) { const regex = new RegExp(`^##\\s+${headingText}\\s*$`, "m"); const match = regex.exec(source); if (!match) fail3(`${label}: required overview H2 is missing`); const headingEnd = source.indexOf("\n", match.index); const contentStart = headingEnd < 0 ? source.length : headingEnd + 1; const end = nextBoundary(source, contentStart, () => false); const body = source.slice(contentStart, end).trim(); if (!body) fail3(`${label}: required overview H2 is empty`); return source.slice(match.index, end).trimEnd(); } function deepFreeze4(value) { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const child of Object.values(value)) deepFreeze4(child); Object.freeze(value); } return value; } function buildDocsResourceMap2(languageSource, recipesSource) { const languageUri = "ksql://language-reference"; const recipesUri = "ksql://recipes"; const languageSections = parseRequiredSections(languageSource, { label: "language reference", count: 26, headingPattern: /^##\s+([1-9]|1\d|2[0-6])\.\s+(.+)$/gm, keyFor: (number4) => `${String(number4).padStart(2, "0")}-${LANGUAGE_SLUGS[number4 - 1]}`, uriBase: languageUri, // Decimal H2 headings (10.1, 17.1, etc.) belong to their integer parent chapter. ignoreBoundary: (heading) => /^\d+\.\d+\s+/.test(heading) }); const recipeSections = parseRequiredSections(recipesSource, { label: "recipes", count: 12, headingPattern: /^##\s+R([1-9]|1[0-2])\.\s+(.+)$/gm, keyFor: (number4) => `r${number4}`, uriBase: recipesUri, ignoreBoundary: () => false }); const languageTitle = documentTitle(languageSource, "language reference"); const recipesTitle = documentTitle(recipesSource, "recipes"); const recipePrinciples = extractH2Section( recipesSource, "\u8A2D\u8A08\u539F\u5247\uFF08\u30EA\u30E9\u30F3\u53EF\u80FD\u30D0\u30C3\u30C1\uFF09", "recipes" ); return deepFreeze4({ languageReference: { title: languageTitle, index: buildIndex( languageTitle, "docs/ksql_language_reference.md", languageUri, "Syntax and dialect reference for kSQL. Read only the section needed for the current task.", languageSections ), sections: languageSections }, recipes: { title: recipesTitle, index: buildIndex( recipesTitle, "docs/ksql_batch_recipes.md", recipesUri, "Safe, rerunnable batch design recipes for CLI, MCP, and the plugin.", recipeSections, recipePrinciples ), sections: recipeSections } }); } module2.exports = { LANGUAGE_SLUGS, buildDocsResourceMap: buildDocsResourceMap2 }; } }); // src/mcp/index.ts var index_exports = {}; __export(index_exports, { KSQL_MCP_INSTRUCTIONS: () => KSQL_MCP_INSTRUCTIONS, createServer: () => createServer, main: () => main }); module.exports = __toCommonJS(index_exports); init_define_KSQL_DOCS(); // node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js init_define_KSQL_DOCS(); // node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js init_define_KSQL_DOCS(); // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js init_define_KSQL_DOCS(); // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js init_define_KSQL_DOCS(); // node_modules/zod/v3/errors.js init_define_KSQL_DOCS(); // node_modules/zod/v3/locales/en.js init_define_KSQL_DOCS(); // node_modules/zod/v3/ZodError.js init_define_KSQL_DOCS(); // node_modules/zod/v3/helpers/util.js init_define_KSQL_DOCS(); var util; (function(util2) { util2.assertEqual = (_) => { }; function assertIs2(_arg) { } util2.assertIs = assertIs2; function assertNever2(_x) { throw new Error(); } util2.assertNever = assertNever2; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { const keys = []; for (const key in object3) { if (Object.prototype.hasOwnProperty.call(object3, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues2(array2, separator = " | ") { return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues2; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; // node_modules/zod/v3/ZodError.js var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var ZodError = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const fieldErrors = { _errors: [] }; const processError = (error51) => { for (const issue2 of error51.issues) { if (issue2.code === "invalid_union") { issue2.unionErrors.map(processError); } else if (issue2.code === "invalid_return_type") { processError(issue2.returnTypeError); } else if (issue2.code === "invalid_arguments") { processError(issue2.argumentsError); } else if (issue2.path.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i = 0; while (i < issue2.path.length) { const el = issue2.path[i]; const terminal = i === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue2) => issue2.message) { const fieldErrors = /* @__PURE__ */ Object.create(null); const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { const firstEl = sub.path[0]; fieldErrors[firstEl] = fieldErrors[firstEl] || []; fieldErrors[firstEl].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError.create = (issues) => { const error51 = new ZodError(issues); return error51; }; // node_modules/zod/v3/locales/en.js var errorMap = (issue2, _ctx) => { let message; switch (issue2.code) { case ZodIssueCode.invalid_type: if (issue2.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue2.expected}, received ${issue2.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue2.validation === "object") { if ("includes" in issue2.validation) { message = `Invalid input: must include "${issue2.validation.includes}"`; if (typeof issue2.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; } } else if ("startsWith" in issue2.validation) { message = `Invalid input: must start with "${issue2.validation.startsWith}"`; } else if ("endsWith" in issue2.validation) { message = `Invalid input: must end with "${issue2.validation.endsWith}"`; } else { util.assertNever(issue2.validation); } } else if (issue2.validation !== "regex") { message = `Invalid ${issue2.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue2.type === "array") message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; else if (issue2.type === "string") message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; else if (issue2.type === "number") message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; else if (issue2.type === "bigint") message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; else if (issue2.type === "date") message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue2.type === "array") message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; else if (issue2.type === "string") message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; else if (issue2.type === "number") message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; else if (issue2.type === "bigint") message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; else if (issue2.type === "date") message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue2.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue2); } return { message }; }; var en_default = errorMap; // node_modules/zod/v3/errors.js var overrideErrorMap = en_default; function getErrorMap() { return overrideErrorMap; } // node_modules/zod/v3/helpers/parseUtil.js init_define_KSQL_DOCS(); var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage2 = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); for (const map2 of maps) { errorMessage2 = map2(fullIssue, { data, defaultError: errorMessage2 }).message; } return { ...issueData, path: fullPath, message: errorMessage2 }; }; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue2 = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === en_default ? void 0 : en_default // then global default map ].filter((x) => !!x) }); ctx.common.issues.push(issue2); } var ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value }); } return _ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x) => x.status === "aborted"; var isDirty = (x) => x.status === "dirty"; var isValid = (x) => x.status === "valid"; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; // node_modules/zod/v3/types.js init_define_KSQL_DOCS(); // node_modules/zod/v3/helpers/errorUtil.js init_define_KSQL_DOCS(); var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); // node_modules/zod/v3/types.js var ParseInputLazyPath = class { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error51 = new ZodError(ctx.common.issues); this._error = error51; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType = class { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { const ctx = { common: { issues: [], async: params?.async ?? false, contextualErrorMap: params?.errorMap }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err) { if (err?.message?.toLowerCase()?.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params?.errorMap, async: true }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check2, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check2(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check2, refinementData) { return this._refinement((val, ctx) => { if (!check2(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform2) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform: transform2 } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; var emojiRegex; var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; var dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version2) { if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT(jwt2, alg) { if (!jwtRegex.test(jwt2)) return false; try { const [header] = jwt2.split("."); if (!header) return false; const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base643)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version2) { if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { return true; } return false; } var ZodString = class _ZodString2 extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.length < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.length > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "length") { const tooBig = input.data.length > check2.value; const tooSmall = input.data.length < check2.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } status.dirty(); } } else if (check2.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "url") { try { new URL(input.data); } catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "regex") { check2.regex.lastIndex = 0; const testResult = check2.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "trim") { input.data = input.data.trim(); } else if (check2.kind === "includes") { if (!input.data.includes(check2.value, check2.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check2.value, position: check2.position }, message: check2.message }); status.dirty(); } } else if (check2.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check2.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check2.kind === "startsWith") { if (!input.data.startsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "endsWith") { if (!input.data.endsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "datetime") { const regex = datetimeRegex(check2); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check2.message }); status.dirty(); } } else if (check2.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "date", message: check2.message }); status.dirty(); } } else if (check2.kind === "time") { const regex = timeRegex(check2); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check2.message }); status.dirty(); } } else if (check2.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ip") { if (!isValidIP(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "jwt") { if (!isValidJWT(input.data, check2.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cidr") { if (!isValidCidr(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message) }); } _addCheck(check2) { return new _ZodString2({ ...this._def, checks: [...this._def.checks, check2] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } base64url(message) { return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message) }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof options?.precision === "undefined" ? null : options?.precision, offset: options?.offset ?? false, local: options?.local ?? false, ...errorUtil.errToObj(options?.message) }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options }); } return this._addCheck({ kind: "time", precision: typeof options?.precision === "undefined" ? null : options?.precision, ...errorUtil.errToObj(options?.message) }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options?.position, ...errorUtil.errToObj(options?.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch) => ch.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get isBase64url() { return !!this._def.checks.find((ch) => ch.kind === "base64url"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodString.create = (params) => { return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } var ZodNumber = class _ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check2 of this._def.checks) { if (check2.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check2.message }); status.dirty(); } } else if (check2.kind === "min") { const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check2.value, type: "number", inclusive: check2.inclusive, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check2.value, type: "number", inclusive: check2.inclusive, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "multipleOf") { if (floatSafeRemainder(input.data, check2.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check2.value, message: check2.message }); status.dirty(); } } else if (check2.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodNumber({ ...this._def, checks: [...this._def.checks, check2] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } get isFinite() { let max = null; let min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodBigInt = class _ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { try { input.data = BigInt(input.data); } catch { return this._getInvalidInput(input); } } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const check2 of this._def.checks) { if (check2.kind === "min") { const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check2.value, inclusive: check2.inclusive, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check2.value, inclusive: check2.inclusive, message: check2.message }); status.dirty(); } } else if (check2.kind === "multipleOf") { if (input.data % check2.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check2.value, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodBigInt({ ...this._def, checks: [...this._def.checks, check2] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodBigInt.create = (params) => { return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; var ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodDate = class _ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (Number.isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.getTime() < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check2.message, inclusive: true, exact: false, minimum: check2.value, type: "date" }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.getTime() > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check2.message, inclusive: true, exact: false, maximum: check2.value, type: "date" }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check2) { return new _ZodDate({ ...this._def, checks: [...this._def.checks, check2] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } }; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: params?.coerce || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny = class extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } }; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown = class extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } }; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever = class extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } }; ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; var ZodVoid = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray = class _ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: tooSmall ? def.exactLength.value : void 0, maximum: tooBig ? def.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema) { if (schema instanceof ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema._def, shape: () => newShape }); } else if (schema instanceof ZodArray) { return new ZodArray({ ...schema._def, type: deepPartialify(schema.element) }); } else if (schema instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple) { return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } var ZodObject = class _ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue2, ctx) => { const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; if (issue2.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema) { return this.augment({ [key]: schema }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new _ZodObject({ ...this._def, catchall: index }); } pick(mask) { const shape = {}; for (const key of util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; for (const key of util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } } return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; var ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [void 0]; } else if (type instanceof ZodNull) { return [null]; } else if (type instanceof ZodOptional) { return [void 0, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } var ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple = class _ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord = class _ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; var ZodMap = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; var ZodSet = class _ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; var ZodFunction = class _ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error51) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error51 } }); } function makeReturnsIssue(returns, error51) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error51 } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { const me = this; return OK(async function(...args) { const error51 = new ZodError([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { error51.addIssue(makeArgsIssue(args, e)); throw error51; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { error51.addIssue(makeReturnsIssue(result, e)); throw error51; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new _ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new _ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new _ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; var ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral = class extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum = class _ZodEnum extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(this._def.values); } if (!this._cache.has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values, newDef = this._def) { return _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; ZodEnum.create = createZodEnum; var ZodNativeEnum = class extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return INVALID; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return INVALID; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess2 }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN = class extends ZodType { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var ZodBranded = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; var ZodPipeline = class _ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a, b) { return new _ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; var ZodReadonly = class extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } }; ZodReadonly.create = (type, params) => { return new ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; var late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind3) { ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var stringType = ZodString.create; var numberType = ZodNumber.create; var nanType = ZodNaN.create; var bigIntType = ZodBigInt.create; var booleanType = ZodBoolean.create; var dateType = ZodDate.create; var symbolType = ZodSymbol.create; var undefinedType = ZodUndefined.create; var nullType = ZodNull.create; var anyType = ZodAny.create; var unknownType = ZodUnknown.create; var neverType = ZodNever.create; var voidType = ZodVoid.create; var arrayType = ZodArray.create; var objectType = ZodObject.create; var strictObjectType = ZodObject.strictCreate; var unionType = ZodUnion.create; var discriminatedUnionType = ZodDiscriminatedUnion.create; var intersectionType = ZodIntersection.create; var tupleType = ZodTuple.create; var recordType = ZodRecord.create; var mapType = ZodMap.create; var setType = ZodSet.create; var functionType = ZodFunction.create; var lazyType = ZodLazy.create; var literalType = ZodLiteral.create; var enumType = ZodEnum.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; // node_modules/zod/v4/mini/external.js init_define_KSQL_DOCS(); // node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, $ZodArray: () => $ZodArray, $ZodAsyncError: () => $ZodAsyncError, $ZodBase64: () => $ZodBase64, $ZodBase64URL: () => $ZodBase64URL, $ZodBigInt: () => $ZodBigInt, $ZodBigIntFormat: () => $ZodBigIntFormat, $ZodBoolean: () => $ZodBoolean, $ZodCIDRv4: () => $ZodCIDRv4, $ZodCIDRv6: () => $ZodCIDRv6, $ZodCUID: () => $ZodCUID, $ZodCUID2: () => $ZodCUID2, $ZodCatch: () => $ZodCatch, $ZodCheck: () => $ZodCheck, $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, $ZodCheckEndsWith: () => $ZodCheckEndsWith, $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, $ZodCheckIncludes: () => $ZodCheckIncludes, $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, $ZodCheckLessThan: () => $ZodCheckLessThan, $ZodCheckLowerCase: () => $ZodCheckLowerCase, $ZodCheckMaxLength: () => $ZodCheckMaxLength, $ZodCheckMaxSize: () => $ZodCheckMaxSize, $ZodCheckMimeType: () => $ZodCheckMimeType, $ZodCheckMinLength: () => $ZodCheckMinLength, $ZodCheckMinSize: () => $ZodCheckMinSize, $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, $ZodCheckStartsWith: () => $ZodCheckStartsWith, $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, $ZodE164: () => $ZodE164, $ZodEmail: () => $ZodEmail, $ZodEmoji: () => $ZodEmoji, $ZodEncodeError: () => $ZodEncodeError, $ZodEnum: () => $ZodEnum, $ZodError: () => $ZodError, $ZodExactOptional: () => $ZodExactOptional, $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, $ZodISODateTime: () => $ZodISODateTime, $ZodISODuration: () => $ZodISODuration, $ZodISOTime: () => $ZodISOTime, $ZodIntersection: () => $ZodIntersection, $ZodJWT: () => $ZodJWT, $ZodKSUID: () => $ZodKSUID, $ZodLazy: () => $ZodLazy, $ZodLiteral: () => $ZodLiteral, $ZodMAC: () => $ZodMAC, $ZodMap: () => $ZodMap, $ZodNaN: () => $ZodNaN, $ZodNanoID: () => $ZodNanoID, $ZodNever: () => $ZodNever, $ZodNonOptional: () => $ZodNonOptional, $ZodNull: () => $ZodNull, $ZodNullable: () => $ZodNullable, $ZodNumber: () => $ZodNumber, $ZodNumberFormat: () => $ZodNumberFormat, $ZodObject: () => $ZodObject, $ZodObjectJIT: () => $ZodObjectJIT, $ZodOptional: () => $ZodOptional, $ZodPipe: () => $ZodPipe, $ZodPrefault: () => $ZodPrefault, $ZodPreprocess: () => $ZodPreprocess, $ZodPromise: () => $ZodPromise, $ZodReadonly: () => $ZodReadonly, $ZodRealError: () => $ZodRealError, $ZodRecord: () => $ZodRecord, $ZodRegistry: () => $ZodRegistry, $ZodSet: () => $ZodSet, $ZodString: () => $ZodString, $ZodStringFormat: () => $ZodStringFormat, $ZodSuccess: () => $ZodSuccess, $ZodSymbol: () => $ZodSymbol, $ZodTemplateLiteral: () => $ZodTemplateLiteral, $ZodTransform: () => $ZodTransform, $ZodTuple: () => $ZodTuple, $ZodType: () => $ZodType, $ZodULID: () => $ZodULID, $ZodURL: () => $ZodURL, $ZodUUID: () => $ZodUUID, $ZodUndefined: () => $ZodUndefined, $ZodUnion: () => $ZodUnion, $ZodUnknown: () => $ZodUnknown, $ZodVoid: () => $ZodVoid, $ZodXID: () => $ZodXID, $ZodXor: () => $ZodXor, $brand: () => $brand, $constructor: () => $constructor, $input: () => $input, $output: () => $output, Doc: () => Doc, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, _any: () => _any, _array: () => _array, _base64: () => _base64, _base64url: () => _base64url, _bigint: () => _bigint, _boolean: () => _boolean, _catch: () => _catch, _check: () => _check, _cidrv4: () => _cidrv4, _cidrv6: () => _cidrv6, _coercedBigint: () => _coercedBigint, _coercedBoolean: () => _coercedBoolean, _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, _date: () => _date, _decode: () => _decode, _decodeAsync: () => _decodeAsync, _default: () => _default, _discriminatedUnion: () => _discriminatedUnion, _e164: () => _e164, _email: () => _email, _emoji: () => _emoji2, _encode: () => _encode, _encodeAsync: () => _encodeAsync, _endsWith: () => _endsWith, _enum: () => _enum, _file: () => _file, _float32: () => _float32, _float64: () => _float64, _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, _includes: () => _includes, _int: () => _int, _int32: () => _int32, _int64: () => _int64, _intersection: () => _intersection, _ipv4: () => _ipv4, _ipv6: () => _ipv6, _isoDate: () => _isoDate, _isoDateTime: () => _isoDateTime, _isoDuration: () => _isoDuration, _isoTime: () => _isoTime, _jwt: () => _jwt, _ksuid: () => _ksuid, _lazy: () => _lazy, _length: () => _length, _literal: () => _literal, _lowercase: () => _lowercase, _lt: () => _lt, _lte: () => _lte, _mac: () => _mac, _map: () => _map, _max: () => _lte, _maxLength: () => _maxLength, _maxSize: () => _maxSize, _mime: () => _mime, _min: () => _gte, _minLength: () => _minLength, _minSize: () => _minSize, _multipleOf: () => _multipleOf, _nan: () => _nan, _nanoid: () => _nanoid, _nativeEnum: () => _nativeEnum, _negative: () => _negative, _never: () => _never, _nonnegative: () => _nonnegative, _nonoptional: () => _nonoptional, _nonpositive: () => _nonpositive, _normalize: () => _normalize, _null: () => _null2, _nullable: () => _nullable, _number: () => _number, _optional: () => _optional, _overwrite: () => _overwrite, _parse: () => _parse, _parseAsync: () => _parseAsync, _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, _property: () => _property, _readonly: () => _readonly, _record: () => _record, _refine: () => _refine, _regex: () => _regex, _safeDecode: () => _safeDecode, _safeDecodeAsync: () => _safeDecodeAsync, _safeEncode: () => _safeEncode, _safeEncodeAsync: () => _safeEncodeAsync, _safeParse: () => _safeParse, _safeParseAsync: () => _safeParseAsync, _set: () => _set, _size: () => _size, _slugify: () => _slugify, _startsWith: () => _startsWith, _string: () => _string, _stringFormat: () => _stringFormat, _stringbool: () => _stringbool, _success: () => _success, _superRefine: () => _superRefine, _symbol: () => _symbol, _templateLiteral: () => _templateLiteral, _toLowerCase: () => _toLowerCase, _toUpperCase: () => _toUpperCase, _transform: () => _transform, _trim: () => _trim, _tuple: () => _tuple, _uint32: () => _uint32, _uint64: () => _uint64, _ulid: () => _ulid, _undefined: () => _undefined2, _union: () => _union, _unknown: () => _unknown, _uppercase: () => _uppercase, _url: () => _url, _uuid: () => _uuid, _uuidv4: () => _uuidv4, _uuidv6: () => _uuidv6, _uuidv7: () => _uuidv7, _void: () => _void, _xid: () => _xid, _xor: () => _xor, clone: () => clone, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, decode: () => decode, decodeAsync: () => decodeAsync, describe: () => describe, encode: () => encode, encodeAsync: () => encodeAsync, extractDefs: () => extractDefs, finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, initializeContext: () => initializeContext, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, isValidJWT: () => isValidJWT2, locales: () => locales_exports, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, prettifyError: () => prettifyError, process: () => process2, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, safeDecodeAsync: () => safeDecodeAsync, safeEncode: () => safeEncode, safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, treeifyError: () => treeifyError, util: () => util_exports, version: () => version }); init_define_KSQL_DOCS(); // node_modules/zod/v4/core/core.js init_define_KSQL_DOCS(); var _a; var NEVER = /* @__PURE__ */ Object.freeze({ status: "aborted" }); // @__NO_SIDE_EFFECTS__ function $constructor(name, initializer3, params) { function init(inst, def) { if (!inst._zod) { Object.defineProperty(inst, "_zod", { value: { def, constr: _, traits: /* @__PURE__ */ new Set() }, enumerable: false }); } if (inst._zod.traits.has(name)) { return; } inst._zod.traits.add(name); initializer3(inst, def); const proto = _.prototype; const keys = Object.keys(proto); for (let i = 0; i < keys.length; i++) { const k = keys[i]; if (!(k in inst)) { inst[k] = proto[k].bind(inst); } } } const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name }); function _(def) { var _a3; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a3 = inst._zod).deferred ?? (_a3.deferred = []); for (const fn of inst._zod.deferred) { fn(); } return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name); } }); Object.defineProperty(_, "name", { value: name }); return _; } var $brand = /* @__PURE__ */ Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; var $ZodEncodeError = class extends Error { constructor(name) { super(`Encountered unidirectional transform during encode: ${name}`); this.name = "ZodEncodeError"; } }; (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); var globalConfig = globalThis.__zod_globalConfig; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } // node_modules/zod/v4/core/parse.js init_define_KSQL_DOCS(); // node_modules/zod/v4/core/errors.js init_define_KSQL_DOCS(); // node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, allowsEval: () => allowsEval, assert: () => assert, assertEqual: () => assertEqual, assertIs: () => assertIs, assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, captureStackTrace: () => captureStackTrace, cleanEnum: () => cleanEnum, cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, extend: () => extend, finalizeIssue: () => finalizeIssue, floatSafeRemainder: () => floatSafeRemainder2, getElementAtPath: () => getElementAtPath, getEnumValues: () => getEnumValues, getLengthableOrigin: () => getLengthableOrigin, getParsedType: () => getParsedType2, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, nullish: () => nullish, numKeys: () => numKeys, objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, parsedType: () => parsedType, partial: () => partial, pick: () => pick, prefixIssues: () => prefixIssues, primitiveTypes: () => primitiveTypes, promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, unwrapMessage: () => unwrapMessage }); init_define_KSQL_DOCS(); function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) { } function assertNever(_x) { throw new Error("Unexpected value in exhaustive check"); } function assert(_) { } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); return values; } function joinValues(array2, separator = "|") { return array2.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { const set2 = false; return { get value() { if (!set2) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } throw new Error("cached value already set"); } }; } function nullish(input) { return input === null || input === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder2(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; } var EVALUATING = /* @__PURE__ */ Symbol("evaluating"); function defineLazy(object3, key, getter) { let value = void 0; Object.defineProperty(object3, key, { get() { if (value === EVALUATING) { return void 0; } if (value === void 0) { value = EVALUATING; value = getter(); } return value; }, set(v) { Object.defineProperty(object3, key, { value: v // configurable: true, }); }, configurable: true }); } function objectClone(obj) { return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { const descriptors = Object.getOwnPropertyDescriptors(def); Object.assign(mergedDescriptors, descriptors); } return Object.defineProperties({}, mergedDescriptors); } function cloneDef(schema) { return mergeDefs(schema._zod.def); } function getElementAtPath(obj, path) { if (!path) return obj; return path.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i = 0; i < keys.length; i++) { resolvedObj[keys[i]] = results[i]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } function slugify(input) { return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval = /* @__PURE__ */ cached(() => { if (globalConfig.jitless) { return false; } if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F = Function; new F(""); return true; } catch (_) { return false; } }); function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; if (typeof ctor !== "function") return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function shallowClone(o) { if (isPlainObject(o)) return { ...o }; if (Array.isArray(o)) return [...o]; if (o instanceof Map) return new Map(o); if (o instanceof Set) return new Set(o); return o; } function numKeys(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } var getParsedType2 = (data) => { const t = typeof data; switch (t) { case "undefined": return "undefined"; case "string": return "string"; case "number": return Number.isNaN(data) ? "nan" : "number"; case "boolean": return "boolean"; case "function": return "function"; case "bigint": return "bigint"; case "symbol": return "symbol"; case "object": if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { return "date"; } if (typeof File !== "undefined" && data instanceof File) { return "file"; } return "object"; default: throw new Error(`Unknown data type: ${t}`); } }; var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); var primitiveTypes = /* @__PURE__ */ new Set([ "string", "number", "bigint", "boolean", "symbol", "undefined" ]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== void 0) { if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_, prop, receiver) { target ?? (target = getter()); return Reflect.get(target, prop, receiver); }, set(_, prop, value, receiver) { target ?? (target = getter()); return Reflect.set(target, prop, value, receiver); }, has(_, prop) { target ?? (target = getter()); return Reflect.has(target, prop); }, deleteProperty(_, prop) { target ?? (target = getter()); return Reflect.deleteProperty(target, prop); }, ownKeys(_) { target ?? (target = getter()); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_, prop) { target ?? (target = getter()); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_, prop, descriptor) { target ?? (target = getter()); return Reflect.defineProperty(target, prop, descriptor); } }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const newShape = {}; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function omit(schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const newShape = { ...schema._zod.def.shape }; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { const existingShape = schema._zod.def.shape; for (const key in shape) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; } }); return clone(schema, def); } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; } }); return clone(schema, def); } function merge(a, b) { if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } const def = mergeDefs(a._zod.def, { get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp(this, "shape", _shape); return _shape; }, get catchall() { return b._zod.def.catchall; }, checks: b._zod.def.checks ?? [] }); return clone(a, def); } function partial(Class2, schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".partial() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } else { for (const key in oldShape) { shape[key] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } assignProp(this, "shape", shape); return shape; }, checks: [] }); return clone(schema, def); } function required(Class2, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = new Class2({ type: "nonoptional", innerType: oldShape[key] }); } } else { for (const key in oldShape) { shape[key] = new Class2({ type: "nonoptional", innerType: oldShape[key] }); } } assignProp(this, "shape", shape); return shape; } }); return clone(schema, def); } function aborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue !== true) { return true; } } return false; } function explicitlyAborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue === false) { return true; } } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a3; (_a3 = iss).path ?? (_a3.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config2) { const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; rest.path ?? (rest.path = []); rest.message = message; if (ctx?.reportInput) { rest.input = _input; } return rest; } function getSizableOrigin(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function parsedType(data) { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "nan" : "number"; } case "object": { if (data === null) { return "null"; } if (Array.isArray(data)) { return "array"; } const obj = data; if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { return obj.constructor.name; } } } return t; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return { ...iss }; } function cleanEnum(obj) { return Object.entries(obj).filter(([k, _]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } function base64ToUint8Array(base643) { const binaryString = atob(base643); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } return bytes; } function uint8ArrayToBase64(bytes) { let binaryString = ""; for (let i = 0; i < bytes.length; i++) { binaryString += String.fromCharCode(bytes[i]); } return btoa(binaryString); } function base64urlToUint8Array(base64url3) { const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); const padding = "=".repeat((4 - base643.length % 4) % 4); return base64ToUint8Array(base643 + padding); } function uint8ArrayToBase64url(bytes) { return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } function hexToUint8Array(hex3) { const cleanHex = hex3.replace(/^0x/, ""); if (cleanHex.length % 2 !== 0) { throw new Error("Invalid hex string length"); } const bytes = new Uint8Array(cleanHex.length / 2); for (let i = 0; i < cleanHex.length; i += 2) { bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); } return bytes; } function uint8ArrayToHex(bytes) { return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); } var Class = class { constructor(..._args) { } }; // node_modules/zod/v4/core/errors.js var initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false }); Object.defineProperty(inst, "issues", { value: def, enumerable: false }); inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false }); }; var $ZodError = $constructor("$ZodError", initializer); var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); function flattenError(error51, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error51.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } function formatError(error51, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; const processError = (error52, path = []) => { for (const issue2 of error52.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }, [...path, ...issue2.path]); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }, [...path, ...issue2.path]); } else { const fullpath = [...path, ...issue2.path]; if (fullpath.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i++; } } } } }; processError(error51); return fieldErrors; } function treeifyError(error51, mapper = (issue2) => issue2.message) { const result = { errors: [] }; const processError = (error52, path = []) => { var _a3, _b; for (const issue2 of error52.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }, [...path, ...issue2.path]); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }, [...path, ...issue2.path]); } else { const fullpath = [...path, ...issue2.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue2)); continue; } let curr = result; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue2)); } i++; } } } }; processError(error51); return result; } function toDotPath(_path) { const segs = []; const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); for (const seg of path) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error51) { const lines = []; const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) lines.push(` \u2192 at ${toDotPath(issue2.path)}`); } return lines.join("\n"); } // node_modules/zod/v4/core/parse.js var _parse = (_Err) => (schema, value, _ctx, _params) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, _params?.callee); throw e; } return result.value; }; var parse = /* @__PURE__ */ _parse($ZodRealError); var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, params?.callee); throw e; } return result.value; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } return result.issues.length ? { success: false, error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); var _encode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _parse(_Err)(schema, value, ctx); }; var encode = /* @__PURE__ */ _encode($ZodRealError); var _decode = (_Err) => (schema, value, _ctx) => { return _parse(_Err)(schema, value, _ctx); }; var decode = /* @__PURE__ */ _decode($ZodRealError); var _encodeAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _parseAsync(_Err)(schema, value, ctx); }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); var _decodeAsync = (_Err) => async (schema, value, _ctx) => { return _parseAsync(_Err)(schema, value, _ctx); }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _safeParse(_Err)(schema, value, ctx); }; var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); var _safeDecode = (_Err) => (schema, value, _ctx) => { return _safeParse(_Err)(schema, value, _ctx); }; var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _safeParseAsync(_Err)(schema, value, ctx); }; var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { return _safeParseAsync(_Err)(schema, value, _ctx); }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); // node_modules/zod/v4/core/schemas.js init_define_KSQL_DOCS(); // node_modules/zod/v4/core/checks.js init_define_KSQL_DOCS(); // node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { base64: () => base64, base64url: () => base64url, bigint: () => bigint, boolean: () => boolean, browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, cuid: () => cuid, cuid2: () => cuid2, date: () => date, datetime: () => datetime, domain: () => domain, duration: () => duration, e164: () => e164, email: () => email, emoji: () => emoji, extendedDuration: () => extendedDuration, guid: () => guid, hex: () => hex, hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, ipv6: () => ipv6, ksuid: () => ksuid, lowercase: () => lowercase, mac: () => mac, md5_base64: () => md5_base64, md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, sha1_base64: () => sha1_base64, sha1_base64url: () => sha1_base64url, sha1_hex: () => sha1_hex, sha256_base64: () => sha256_base64, sha256_base64url: () => sha256_base64url, sha256_hex: () => sha256_hex, sha384_base64: () => sha384_base64, sha384_base64url: () => sha384_base64url, sha384_hex: () => sha384_hex, sha512_base64: () => sha512_base64, sha512_base64url: () => sha512_base64url, sha512_hex: () => sha512_hex, string: () => string, time: () => time, ulid: () => ulid, undefined: () => _undefined, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, uuid: () => uuid, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, xid: () => xid }); init_define_KSQL_DOCS(); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; var uuid = (version2) => { if (!version2) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; var mac = (delimiter) => { const escapedDelim = escapeRegex(delimiter ?? ":"); return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url = /^[A-Za-z0-9_-]*$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { const time3 = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); const timeRegex2 = `${time3}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); } var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; var bigint = /^-?\d+n?$/; var integer = /^-?\d+$/; var number = /^-?\d+(?:\.\d+)?$/; var boolean = /^(?:true|false)$/i; var _null = /^null$/i; var _undefined = /^undefined$/i; var lowercase = /^[^A-Z]*$/; var uppercase = /^[^a-z]*$/; var hex = /^[0-9a-fA-F]*$/; function fixedBase64(bodyLength, padding) { return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); } function fixedBase64url(length) { return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); } var md5_hex = /^[0-9a-fA-F]{32}$/; var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); var md5_base64url = /* @__PURE__ */ fixedBase64url(22); var sha1_hex = /^[0-9a-fA-F]{40}$/; var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); var sha256_hex = /^[0-9a-fA-F]{64}$/; var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); var sha384_hex = /^[0-9a-fA-F]{96}$/; var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); // node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a3; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a3 = inst._zod).onattach ?? (_a3.onattach = []); }); var numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { var _a3; (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ origin: typeof payload.value, code: "not_multiple_of", divisor: def.value, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck.init(inst, def); def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); } }; }); var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); } }; }); var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a3; $ZodCheck.init(inst, def); (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push({ origin: getSizableOrigin(input), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a3; $ZodCheck.init(inst, def); (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length >= def.minimum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a3; $ZodCheck.init(inst, def); (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.length; bag.maximum = def.length; bag.length = def.length; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length === def.length) return; const origin = getLengthableOrigin(input); const tooBig = length > def.length; payload.issues.push({ origin, ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a3, _b; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a3 = inst._zod).check ?? (_a3.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: def.format, input: payload.value, ...def.pattern ? { pattern: def.pattern.toString() } : {}, inst, continue: !def.abort }); }); else (_b = inst._zod).check ?? (_b.check = () => { }); }); var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { $ZodCheckStringFormat.init(inst, def); inst._zod.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: payload.value, pattern: def.pattern.toString(), inst, continue: !def.abort }); }; }); var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { def.pattern ?? (def.pattern = lowercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { def.pattern ?? (def.pattern = uppercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort }); }; }); function handleCheckPropertyResult(result, payload, property) { if (result.issues.length) { payload.issues.push(...prefixIssues(property, result.issues)); } } var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { const result = def.schema._zod.run({ value: payload.value[def.property], issues: [] }, {}); if (result instanceof Promise) { return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); } handleCheckPropertyResult(result, payload, def.property); return; }; }); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst2) => { inst2._zod.bag.mime = def.mime; }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; payload.issues.push({ code: "invalid_value", values: def.mime, input: payload.value.type, inst, continue: !def.abort }); }; }); var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); // node_modules/zod/v4/core/doc.js init_define_KSQL_DOCS(); var Doc = class { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn) { this.indent += 1; fn(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x) => x); const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); for (const line of dedented) { this.content.push(line); } } compile() { const F = Function; const args = this?.args; const content = this?.content ?? [``]; const lines = [...content.map((x) => ` ${x}`)]; return new F(...args, lines.join("\n")); } }; // node_modules/zod/v4/core/versions.js init_define_KSQL_DOCS(); var version = { major: 4, minor: 4, patch: 3 }; // node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a3; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; const checks = [...inst._zod.def.checks ?? []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { (_a3 = inst._zod).deferred ?? (_a3.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks2, ctx) => { let isAborted2 = aborted(payload); let asyncResult; for (const ch of checks2) { if (ch._zod.def.when) { if (explicitlyAborted(payload)) continue; const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted2) { continue; } const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && ctx?.async === false) { throw new $ZodAsyncError(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted2) isAborted2 = aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted2) isAborted2 = aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; const handleCanaryResult = (canary, payload, ctx) => { if (aborted(canary)) { canary.aborted = true; return canary; } const checkResult = runChecks(payload, checks, ctx); if (checkResult instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); } return inst._zod.parse(checkResult, ctx); }; inst._zod.run = (payload, ctx) => { if (ctx.skipChecks) { return inst._zod.parse(payload, ctx); } if (ctx.direction === "backward") { const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); if (canary instanceof Promise) { return canary.then((canary2) => { return handleCanaryResult(canary2, payload, ctx); }); } return handleCanaryResult(canary, payload, ctx); } const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result2) => runChecks(result2, checks, ctx)); } return runChecks(result, checks, ctx); }; } defineLazy(inst, "~standard", () => ({ validate: (value) => { try { const r = safeParse(inst, value); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } }, vendor: "zod", version: 1 })); }); var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_2) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { $ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); }); var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { def.pattern ?? (def.pattern = guid); $ZodStringFormat.init(inst, def); }); var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { if (def.version) { const versionMap = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }; const v = versionMap[def.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ?? (def.pattern = uuid(v)); } else def.pattern ?? (def.pattern = uuid()); $ZodStringFormat.init(inst, def); }); var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); if (!def.normalize && def.protocol?.source === httpProtocol.source) { if (!/^https?:\/\//i.test(trimmed)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid URL format", input: payload.value, inst, continue: !def.abort }); return; } } const url2 = new URL(trimmed); if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url2.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: def.hostname.source, input: payload.value, inst, continue: !def.abort }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort }); } } if (def.normalize) { payload.value = url2.href; } else { payload.value = trimmed; } return; } catch (_) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { def.pattern ?? (def.pattern = emoji()); $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { def.pattern ?? (def.pattern = nanoid); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { def.pattern ?? (def.pattern = cuid); $ZodStringFormat.init(inst, def); }); var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { def.pattern ?? (def.pattern = cuid2); $ZodStringFormat.init(inst, def); }); var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { def.pattern ?? (def.pattern = ulid); $ZodStringFormat.init(inst, def); }); var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { def.pattern ?? (def.pattern = xid); $ZodStringFormat.init(inst, def); }); var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { def.pattern ?? (def.pattern = ksuid); $ZodStringFormat.init(inst, def); }); var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { def.pattern ?? (def.pattern = datetime(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { def.pattern ?? (def.pattern = date); $ZodStringFormat.init(inst, def); }); var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { def.pattern ?? (def.pattern = time(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { def.pattern ?? (def.pattern = duration); $ZodStringFormat.init(inst, def); }); var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `ipv4`; }); var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const parts = payload.value.split("/"); try { if (parts.length !== 2) throw new Error(); const [address, prefix] = parts; if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); } catch { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort }); } }; }); function isValidBase64(data) { if (data === "") return true; if (/\s/.test(data)) return false; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch { return false; } } var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { def.pattern ?? (def.pattern = base64); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort }); }; }); function isValidBase64URL(data) { if (!base64url.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { def.pattern ?? (def.pattern = base64url); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); function isValidJWT2(token, algorithm = null) { try { const tokensParts = token.split("."); if (tokensParts.length !== 3) return false; const [header] = tokensParts; if (!header) return false; const parsedHeader = JSON.parse(atob(header)); if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; if (!parsedHeader.alg) return false; if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch { return false; } } var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT2(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (def.fn(payload.value)) return; payload.issues.push({ code: "invalid_format", format: def.format, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...received ? { received } : {} }); return payload; }; }); var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst }); return payload; }; }); var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = bigint; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = BigInt(payload.value); } catch (_) { } if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { $ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); }); var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst }); return payload; }; }); var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst }); return payload; }; }); var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst }); return payload; }; }); var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ expected: "never", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst }); return payload; }; }); var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (def.coerce) { try { payload.value = new Date(payload.value); } catch (_err) { } } const input = payload.value; const isDate = input instanceof Date; const isValidDate = isDate && !Number.isNaN(input.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", input, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); function handleArrayResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst }); return payload; } payload.value = Array(input.length); const proms = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { const isPresent = key in input; if (result.issues.length) { if (isOptionalIn && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } if (!isPresent && !isOptionalIn) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", expected: "nonoptional", input: void 0, path: [key] }); } return; } if (result.value === void 0) { if (isPresent) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } function normalizeDef(def) { const keys = Object.keys(def.shape); for (const k of keys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } function handleCatchall(proms, input, payload, ctx, def, inst) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; const isOptionalIn = _catchall.optin === "optional"; const isOptionalOut = _catchall.optout === "optional"; for (const key in input) { if (key === "__proto__") continue; if (keySet.has(key)) continue; if (t === "never") { unrecognized.push(key); continue; } const r = _catchall.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); } else { handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst }); } if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); } var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc = Object.getOwnPropertyDescriptor(def, "shape"); if (!desc?.get) { const sh = def.shape; Object.defineProperty(def, "shape", { get: () => { const newSh = { ...sh }; Object.defineProperty(def, "shape", { value: newSh }); return newSh; } }); } const _normalized = cached(() => normalizeDef(def)); defineLazy(inst._zod, "propValues", () => { const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); for (const v of field.values) propValues[key].add(v); } } return propValues; }); const isObject2 = isObject; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } payload.value = {}; const proms = []; const shape = value.shape; for (const key of value.keys) { const el = shape[key]; const isOptionalIn = el._zod.optin === "optional"; const isOptionalOut = el._zod.optout === "optional"; const r = el._zod.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); } else { handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); const generateFastpass = (shape) => { const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { const k = esc(key); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } doc.write(`const newResult = {};`); for (const key of normalized.keys) { const id = ids[key]; const k = esc(key); const schema = shape[key]; const isOptionalIn = schema?._zod?.optin === "optional"; const isOptionalOut = schema?._zod?.optout === "optional"; doc.write(`const ${id} = ${parseStr(key)};`); if (isOptionalIn && isOptionalOut) { doc.write(` if (${id}.issues.length) { if (${k} in input) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } else if (!isOptionalIn) { doc.write(` const ${id}_present = ${k} in input; if (${id}.issues.length) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${k}] }); } if (${id}_present) { if (${id}.value === undefined) { newResult[${k}] = undefined; } else { newResult[${k}] = ${id}.value; } } `); } else { doc.write(` if (${id}.issues.length) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); const fn = doc.compile(); return (payload, ctx) => fn(shape, payload, ctx); }; let fastpass; const isObject2 = isObject; const jit = !globalConfig.jitless; const allowsEval2 = allowsEval; const fastEnabled = jit && allowsEval2.value; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); if (!catchall) return payload; return handleCatchall([], input, payload, ctx, value, inst); } return superParse(payload, ctx); }; }); function handleUnionResults(results, final, inst, ctx) { for (const result of results) { if (result.issues.length === 0) { final.value = result.value; return final; } } const nonaborted = results.filter((r) => !aborted(r)); if (nonaborted.length === 1) { final.value = nonaborted[0].value; return nonaborted[0]; } final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); return final; } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); defineLazy(inst._zod, "values", () => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o) => o._zod.pattern)) { const patterns = def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; }); const first = def.options.length === 1 ? def.options[0]._zod.run : null; inst._zod.parse = (payload, ctx) => { if (first) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { if (result.issues.length === 0) return result; results.push(result); } } if (!async) return handleUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleUnionResults(results2, payload, inst, ctx); }); }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { const successes = results.filter((r) => r.issues.length === 0); if (successes.length === 1) { final.value = successes[0].value; return final; } if (successes.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); } else { final.issues.push({ code: "invalid_union", input: final.value, inst, errors: [], inclusive: false }); } return final; } var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { $ZodUnion.init(inst, def); def.inclusive = false; const first = def.options.length === 1 ? def.options[0]._zod.run : null; inst._zod.parse = (payload, ctx) => { if (first) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { results.push(result); } } if (!async) return handleExclusiveUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleExclusiveUnionResults(results2, payload, inst, ctx); }); }; }); var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); for (const val of v) { propValues[k].add(val); } } } return propValues; }); const disc = cached(() => { const opts = def.options; const map2 = /* @__PURE__ */ new Map(); for (const o of opts) { const values = o._zod.propValues?.[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); for (const v of values) { if (map2.has(v)) { throw new Error(`Duplicate discriminator value "${String(v)}"`); } map2.set(v, o); } } return map2; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst }); return payload; } const opt = disc.value.get(input?.[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { return _super(payload, ctx); } payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", discriminator: def.discriminator, options: Array.from(disc.value.keys()), input, path: [def.discriminator], inst }); return payload; }; }); var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; const left = def.left._zod.run({ value: input, issues: [] }, ctx); const right = def.right._zod.run({ value: input, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { return handleIntersectionResults(payload, left2, right2); }); } return handleIntersectionResults(payload, left, right); }; }); function mergeValues2(a, b) { if (a === b) { return { valid: true, data: a }; } if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } if (isPlainObject(a) && isPlainObject(b)) { const bKeys = Object.keys(b); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues2(a[key], b[key]); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [key, ...sharedValue.mergeErrorPath] }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return { valid: false, mergeErrorPath: [] }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues2(itemA, itemB); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [index, ...sharedValue.mergeErrorPath] }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } return { valid: false, mergeErrorPath: [] }; } function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; for (const iss of left.issues) { if (iss.code === "unrecognized_keys") { unrecIssue ?? (unrecIssue = iss); for (const k of iss.keys) { if (!unrecKeys.has(k)) unrecKeys.set(k, {}); unrecKeys.get(k).l = true; } } else { result.issues.push(iss); } } for (const iss of right.issues) { if (iss.code === "unrecognized_keys") { for (const k of iss.keys) { if (!unrecKeys.has(k)) unrecKeys.set(k, {}); unrecKeys.get(k).r = true; } } else { result.issues.push(iss); } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); if (bothKeys.length && unrecIssue) { result.issues.push({ ...unrecIssue, keys: bothKeys }); } if (aborted(result)) return result; const merged = mergeValues2(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ input, inst, expected: "tuple", code: "invalid_type" }); return payload; } payload.value = []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { if (input.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, input, inst, origin: "array" }); return payload; } if (input.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, input, inst, origin: "array" }); } } const itemResults = new Array(items.length); for (let i = 0; i < items.length; i++) { const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; } } if (def.rest) { let i = items.length - 1; const rest = input.slice(items.length); for (const el of rest) { i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((r) => handleTupleResult(r, payload, i))); } else { handleTupleResult(result, payload, i); } } } if (proms.length) { return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); } return handleTupleResults(itemResults, payload, items, input, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { if (items[i]._zod[key] !== "optional") return i + 1; } return 0; } function handleTupleResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } function handleTupleResults(itemResults, final, items, input, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; const isPresent = i < input.length; if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; break; } final.issues.push(...prefixIssues(i, r.issues)); } final.value[i] = r.value; } for (let i = final.value.length - 1; i >= input.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { break; } } return final; } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject(input)) { payload.issues.push({ expected: "record", code: "invalid_type", input, inst }); return payload; } const proms = []; const values = def.keyType._zod.values; if (values) { payload.value = {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (keyResult.issues.length) { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); continue; } const outKey = keyResult.value; const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[outKey] = result.value; } } } let unrecognized; for (const key in input) { if (!recordKeys.has(key)) { unrecognized = unrecognized ?? []; unrecognized.push(key); } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized }); } } else { payload.value = {}; for (const key of Reflect.ownKeys(input)) { if (key === "__proto__") continue; if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; if (checkNumericKey) { const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); if (retryResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (retryResult.issues.length === 0) { keyResult = retryResult; } } if (keyResult.issues.length) { if (def.mode === "loose") { payload.value[key] = input[key]; } else { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); } continue; } const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[keyResult.value] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[keyResult.value] = result.value; } } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", input, inst }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Map(); for (const [key, value] of input) { const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); })); } else { handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); } else { final.issues.push({ code: "invalid_key", origin: "map", input, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } if (valueResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, valueResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_element", input, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } final.value.set(keyResult.value, valueResult.value); } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Set)) { payload.issues.push({ input, inst, expected: "set", code: "invalid_type" }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Set(); for (const item of input) { const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); } else handleSetResult(result, payload); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleSetResult(result, final) { if (result.issues.length) { final.issues.push(...result.issues); } final.value.add(result.value); } var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); const valuesSet = new Set(values); inst._zod.values = valuesSet; inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (valuesSet.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values, input, inst }); return payload; }; }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); if (def.values.length === 0) { throw new Error("Cannot create literal schema with no valid values"); } const values = new Set(def.values); inst._zod.values = values; inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, input, inst }); return payload; }; }); var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", input, inst }); return payload; }; }); var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { const output = _out instanceof Promise ? _out : Promise.resolve(_out); return output.then((output2) => { payload.value = output2; payload.fallback = true; return payload; }); } if (_out instanceof Promise) { throw new $ZodAsyncError(); } payload.value = _out; payload.fallback = true; return payload; }; }); function handleOptionalResult(result, input) { if (input === void 0 && (result.issues.length || result.fallback)) { return { issues: [], value: void 0 }; } return result; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; }); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { const input = payload.value; const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, input)); return handleOptionalResult(result, input); } if (payload.value === void 0) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleDefaultResult(result2, def)); } return handleDefaultResult(result, def); }; }); function handleDefaultResult(payload, def) { if (payload.value === void 0) { payload.value = def.defaultValue; } return payload; } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { const v = def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleNonOptionalResult(result2, inst)); } return handleNonOptionalResult(result, inst); }; }); function handleNonOptionalResult(payload, inst) { if (!payload.issues.length && payload.value === void 0) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst }); } return payload; } var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError("ZodSuccess"); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }); var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.value; if (result2.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; payload.fallback = true; } return payload; }); } payload.value = result.value; if (result.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; payload.fallback = true; } return payload; }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { payload.issues.push({ input: payload.value, inst, expected: "nan", code: "invalid_type" }); return payload; } return payload; }; }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handlePipeResult(right2, def.in, ctx)); } return handlePipeResult(right, def.in, ctx); } const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handlePipeResult(left2, def.out, ctx)); } return handlePipeResult(left, def.out, ctx); }; }); function handlePipeResult(left, next, ctx) { if (left.issues.length) { left.aborted = true; return left; } return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handleCodecAResult(left2, def, ctx)); } return handleCodecAResult(left, def, ctx); } else { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handleCodecAResult(right2, def, ctx)); } return handleCodecAResult(right, def, ctx); } }; }); function handleCodecAResult(result, def, ctx) { if (result.issues.length) { result.aborted = true; return result; } const direction = ctx.direction || "forward"; if (direction === "forward") { const transformed = def.transform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); } return handleCodecTxResult(result, transformed, def.out, ctx); } else { const transformed = def.reverseTransform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); } return handleCodecTxResult(result, transformed, def.in, ctx); } } function handleCodecTxResult(left, value, nextSchema, ctx) { if (left.issues.length) { left.aborted = true; return left; } return nextSchema._zod.run({ value, issues: left.issues }, ctx); } var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => { $ZodPipe.init(inst, def); }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); } return handleReadonlyResult(result); }; }); function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { if (!part._zod.pattern) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; if (!source) throw new Error(`Invalid template literal part: ${part._zod.traits}`); const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; regexParts.push(source.slice(start, end)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { throw new Error(`Invalid template literal part: ${part}`); } } inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "string", code: "invalid_type" }); return payload; } inst._zod.pattern.lastIndex = 0; if (!inst._zod.pattern.test(payload.value)) { payload.issues.push({ input: payload.value, inst, code: "invalid_format", format: def.format ?? "template_literal", pattern: inst._zod.pattern.source }); return payload; } return payload; }; }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); inst._def = def; inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } return function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; }; }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } return async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; }; }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { payload.issues.push({ code: "invalid_type", expected: "function", input: payload.value, inst }); return payload; } const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; if (hasPromiseOutput) { payload.value = inst.implementAsync(payload.value); } else { payload.value = inst.implement(payload.value); } return payload; }; inst.input = (...args) => { const F = inst.constructor; if (Array.isArray(args[0])) { return new F({ type: "function", input: new $ZodTuple({ type: "tuple", items: args[0], rest: args[1] }), output: inst._def.output }); } return new F({ type: "function", input: args[0], output: inst._def.output }); }; inst.output = (output) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, output }); }; return inst; }); var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }); var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "innerType", () => { const d = def; if (!d._cachedInner) d._cachedInner = def.getter(); return d._cachedInner; }); defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }); var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); inst._zod.parse = (payload, _) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r = def.fn(input); if (r instanceof Promise) { return r.then((r2) => handleRefineResult(r2, payload, input, inst)); } handleRefineResult(r, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { if (!result) { const _iss = { code: "custom", input, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], // incorporates params.error into issue reporting continue: !inst._zod.def.abort // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(issue(_iss)); } } // node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, ca: () => ca_default, cs: () => cs_default, da: () => da_default, de: () => de_default, el: () => el_default, en: () => en_default2, eo: () => eo_default, es: () => es_default, fa: () => fa_default, fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, he: () => he_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, id: () => id_default, is: () => is_default, it: () => it_default, ja: () => ja_default, ka: () => ka_default, kh: () => kh_default, km: () => km_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, nl: () => nl_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, ro: () => ro_default, ru: () => ru_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, th: () => th_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, ur: () => ur_default, uz: () => uz_default, vi: () => vi_default, yo: () => yo_default, zhCN: () => zh_CN_default, zhTW: () => zh_TW_default }); init_define_KSQL_DOCS(); // node_modules/zod/v4/locales/ar.js init_define_KSQL_DOCS(); var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; } return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; if (_issue.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; } case "not_multiple_of": return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; case "unrecognized_keys": return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; case "invalid_union": return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; case "invalid_element": return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; default: return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; } }; }; function ar_default() { return { localeError: error() }; } // node_modules/zod/v4/locales/az.js init_define_KSQL_DOCS(); var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; } return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; if (_issue.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; if (_issue.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; if (_issue.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; case "unrecognized_keys": return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; case "invalid_union": return "Yanl\u0131\u015F d\u0259y\u0259r"; case "invalid_element": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; default: return `Yanl\u0131\u015F d\u0259y\u0259r`; } }; }; function az_default() { return { localeError: error2() }; } // node_modules/zod/v4/locales/be.js init_define_KSQL_DOCS(); function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error3 = () => { const Sizable = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u043B\u0456\u043A", array: "\u043C\u0430\u0441\u0456\u045E" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; } return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; case "invalid_element": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; default: return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; } }; }; function be_default() { return { localeError: error3() }; } // node_modules/zod/v4/locales/bg.js init_define_KSQL_DOCS(); var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0445\u043E\u0434", email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0438\u0432" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; } return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; if (_issue.format === "emoji") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "datetime") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "date") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; if (_issue.format === "time") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "duration") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; case "invalid_element": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; default: return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; } }; }; function bg_default() { return { localeError: error4() }; } // node_modules/zod/v4/locales/ca.js init_define_KSQL_DOCS(); var error5 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entrada", email: "adre\xE7a electr\xF2nica", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; } return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; case "too_big": { const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; const sizing = getSizing(issue2.origin); if (sizing) return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; const sizing = getSizing(issue2.origin); if (sizing) { return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; if (_issue.format === "includes") return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; if (_issue.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; case "unrecognized_keys": return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Clau inv\xE0lida a ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE0lida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general case "invalid_element": return `Element inv\xE0lid a ${issue2.origin}`; default: return `Entrada inv\xE0lida`; } }; }; function ca_default() { return { localeError: error5() }; } // node_modules/zod/v4/locales/cs.js init_define_KSQL_DOCS(); var error6 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" }; const TypeDictionary = { nan: "NaN", number: "\u010D\xEDslo", string: "\u0159et\u011Bzec", function: "funkce", array: "pole" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; } return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; if (_issue.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; if (_issue.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; case "unrecognized_keys": return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; case "invalid_union": return "Neplatn\xFD vstup"; case "invalid_element": return `Neplatn\xE1 hodnota v ${issue2.origin}`; default: return `Neplatn\xFD vstup`; } }; }; function cs_default() { return { localeError: error6() }; } // node_modules/zod/v4/locales/da.js init_define_KSQL_DOCS(); var error7 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, set: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "e-mailadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkesl\xE6t", date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", string: "streng", number: "tal", boolean: "boolean", array: "liste", object: "objekt", set: "s\xE6t", file: "fil" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; } return `Ugyldigt input: forventede ${expected}, fik ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) { return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: skal starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: skal ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: skal indeholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8gle i ${issue2.origin}`; case "invalid_union": return "Ugyldigt input: matcher ingen af de tilladte typer"; case "invalid_element": return `Ugyldig v\xE6rdi i ${issue2.origin}`; default: return `Ugyldigt input`; } }; }; function da_default() { return { localeError: error7() }; } // node_modules/zod/v4/locales/de.js init_define_KSQL_DOCS(); var error8 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "Eingabe", email: "E-Mail-Adresse", url: "URL", emoji: "Emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }; const TypeDictionary = { nan: "NaN", number: "Zahl", array: "Array" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; } return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; } return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; if (_issue.format === "ends_with") return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; if (_issue.format === "includes") return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; if (_issue.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; case "invalid_union": return "Ung\xFCltige Eingabe"; case "invalid_element": return `Ung\xFCltiger Wert in ${issue2.origin}`; default: return `Ung\xFCltige Eingabe`; } }; }; function de_default() { return { localeError: error8() }; } // node_modules/zod/v4/locales/el.js init_define_KSQL_DOCS(); var error9 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2", email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1", date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1", time: "ISO \u03CE\u03C1\u03B1", duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1", ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4", ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6", mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC", cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4", cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6", base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64", base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (typeof issue2.expected === "string" && /^[A-Z]/.test(issue2.expected)) { return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; } return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`; return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`; return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`; if (_issue.format === "regex") return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`; return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`; case "unrecognized_keys": return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`; case "invalid_union": return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"; case "invalid_element": return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`; default: return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`; } }; }; function el_default() { return { localeError: error9() }; } // node_modules/zod/v4/locales/en.js init_define_KSQL_DOCS(); var error10 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" }, map: { unit: "entries", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { // Compatibility: "nan" -> "NaN" for display nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Invalid string: must start with "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue2.divisor}`; case "unrecognized_keys": return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Invalid key in ${issue2.origin}`; case "invalid_union": if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { const opts = issue2.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; default: return `Invalid input`; } }; }; function en_default2() { return { localeError: error10() }; } // node_modules/zod/v4/locales/eo.js init_define_KSQL_DOCS(); var error11 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }; const TypeDictionary = { nan: "NaN", number: "nombro", array: "tabelo", null: "senvalora" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; } return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; if (_issue.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; if (_issue.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; case "unrecognized_keys": return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nevalida \u015Dlosilo en ${issue2.origin}`; case "invalid_union": return "Nevalida enigo"; case "invalid_element": return `Nevalida valoro en ${issue2.origin}`; default: return `Nevalida enigo`; } }; }; function eo_default() { return { localeError: error11() }; } // node_modules/zod/v4/locales/es.js init_define_KSQL_DOCS(); var error12 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN", string: "texto", number: "n\xFAmero", boolean: "booleano", array: "arreglo", object: "objeto", set: "conjunto", file: "archivo", date: "fecha", bigint: "n\xFAmero grande", symbol: "s\xEDmbolo", undefined: "indefinido", null: "nulo", function: "funci\xF3n", map: "mapa", record: "registro", tuple: "tupla", enum: "enumeraci\xF3n", union: "uni\xF3n", literal: "literal", promise: "promesa", void: "vac\xEDo", never: "nunca", unknown: "desconocido", any: "cualquiera" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; } return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) { return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; if (_issue.format === "includes") return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; default: return `Entrada inv\xE1lida`; } }; }; function es_default() { return { localeError: error12() }; } // node_modules/zod/v4/locales/fa.js init_define_KSQL_DOCS(); var error13 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; const TypeDictionary = { nan: "NaN", number: "\u0639\u062F\u062F", array: "\u0622\u0631\u0627\u06CC\u0647" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; } return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; } case "invalid_value": if (issue2.values.length === 1) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; } return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; } if (_issue.format === "ends_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; } if (_issue.format === "includes") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; } if (_issue.format === "regex") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; } return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } case "not_multiple_of": return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; case "unrecognized_keys": return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; case "invalid_union": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; case "invalid_element": return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; default: return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } }; }; function fa_default() { return { localeError: error13() }; } // node_modules/zod/v4/locales/fi.js init_define_KSQL_DOCS(); var error14 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; } return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); } return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); } return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; if (_issue.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; if (_issue.format === "regex") { return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; } return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Virheellinen avain tietueessa"; case "invalid_union": return "Virheellinen unioni"; case "invalid_element": return "Virheellinen arvo joukossa"; default: return `Virheellinen sy\xF6te`; } }; }; function fi_default() { return { localeError: error14() }; } // node_modules/zod/v4/locales/fr.js init_define_KSQL_DOCS(); var error15 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entr\xE9e", email: "adresse e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { string: "cha\xEEne", number: "nombre", int: "entier", boolean: "bool\xE9en", bigint: "grand entier", symbol: "symbole", undefined: "ind\xE9fini", null: "null", never: "jamais", void: "vide", date: "date", array: "tableau", object: "objet", tuple: "tuple", record: "enregistrement", map: "carte", set: "ensemble", file: "fichier", nonoptional: "non-optionnel", nan: "NaN", function: "fonction" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_default() { return { localeError: error15() }; } // node_modules/zod/v4/locales/fr-CA.js init_define_KSQL_DOCS(); var error16 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entr\xE9e", email: "adresse courriel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; } return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u2264" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u2265" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_CA_default() { return { localeError: error16() }; } // node_modules/zod/v4/locales/he.js init_define_KSQL_DOCS(); var error17 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, bigint: { label: "BigInt", gender: "m" }, date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, promise: { label: "Promise", gender: "m" }, NaN: { label: "NaN", gender: "m" }, unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, value: { label: "\u05E2\u05E8\u05DA", gender: "m" } }; const Sizable = { string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } // no unit }; const typeEntry = (t) => t ? TypeNames[t] : void 0; const typeLabel = (t) => { const e = typeEntry(t); if (e) return e.label; return t ?? TypeNames.unknown.label; }; const withDefinite = (t) => `\u05D4${typeLabel(t)}`; const verbFor = (t) => { const e = typeEntry(t); const gender = e?.gender ?? "m"; return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; }; const getSizing = (origin) => { if (!origin) return null; return Sizable[origin] ?? null; }; const FormatDictionary = { regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, cuid2: { label: "cuid2", gender: "m" }, ulid: { label: "ULID", gender: "m" }, xid: { label: "XID", gender: "m" }, ksuid: { label: "KSUID", gender: "m" }, datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, jwt: { label: "JWT", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expectedKey = issue2.expected; const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; } return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; } case "invalid_value": { if (issue2.values.length === 1) { return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; } const stringified = issue2.values.map((v) => stringifyPrimitive(v)); if (issue2.values.length === 2) { return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; } const lastValue = stringified[stringified.length - 1]; const restValues = stringified.slice(0, -1).join(", "); return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; } case "too_big": { const sizing = getSizing(issue2.origin); const subject = withDefinite(issue2.origin ?? "value"); if (issue2.origin === "string") { return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); } if (issue2.origin === "number") { const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; } if (issue2.origin === "array" || issue2.origin === "set") { const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); } const adj = issue2.inclusive ? "<=" : "<"; const be = verbFor(issue2.origin ?? "value"); if (sizing?.unit) { return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; } return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const sizing = getSizing(issue2.origin); const subject = withDefinite(issue2.origin ?? "value"); if (issue2.origin === "string") { return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); } if (issue2.origin === "number") { const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; } if (issue2.origin === "array" || issue2.origin === "set") { const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; if (issue2.minimum === 1 && issue2.inclusive) { const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; } const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); } const adj = issue2.inclusive ? ">=" : ">"; const be = verbFor(issue2.origin ?? "value"); if (sizing?.unit) { return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; if (_issue.format === "regex") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; const nounEntry = FormatDictionary[_issue.format]; const noun = nounEntry?.label ?? _issue.format; const gender = nounEntry?.gender ?? "m"; const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; return `${noun} \u05DC\u05D0 ${adjective}`; } case "not_multiple_of": return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; case "unrecognized_keys": return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": { return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; } case "invalid_union": return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; case "invalid_element": { const place = withDefinite(issue2.origin ?? "array"); return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; } default: return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } }; }; function he_default() { return { localeError: error17() }; } // node_modules/zod/v4/locales/hr.js init_define_KSQL_DOCS(); var error18 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, array: { unit: "stavki", verb: "imati" }, set: { unit: "stavki", verb: "imati" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "unos", email: "email adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum i vrijeme", date: "ISO datum", time: "ISO vrijeme", duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", jwt: "JWT", template_literal: "unos" }; const TypeDictionary = { nan: "NaN", string: "tekst", number: "broj", boolean: "boolean", array: "niz", object: "objekt", set: "skup", file: "datoteka", date: "datum", bigint: "bigint", symbol: "simbol", undefined: "undefined", null: "null", function: "funkcija", map: "mapa" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`; } return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`; return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemenata"}`; return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) { return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`; if (_issue.format === "includes") return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`; if (_issue.format === "regex") return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`; return `Neispravna ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`; case "unrecognized_keys": return `Neprepoznat${issue2.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neispravan klju\u010D u ${TypeDictionary[issue2.origin] ?? issue2.origin}`; case "invalid_union": return "Neispravan unos"; case "invalid_element": return `Neispravna vrijednost u ${TypeDictionary[issue2.origin] ?? issue2.origin}`; default: return `Neispravan unos`; } }; }; function hr_default() { return { localeError: error18() }; } // node_modules/zod/v4/locales/hu.js init_define_KSQL_DOCS(); var error19 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "bemenet", email: "email c\xEDm", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" }; const TypeDictionary = { nan: "NaN", number: "sz\xE1m", array: "t\xF6mb" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; } return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; if (_issue.format === "ends_with") return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; if (_issue.format === "includes") return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; if (_issue.format === "regex") return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; case "unrecognized_keys": return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; case "invalid_union": return "\xC9rv\xE9nytelen bemenet"; case "invalid_element": return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; default: return `\xC9rv\xE9nytelen bemenet`; } }; }; function hu_default() { return { localeError: error19() }; } // node_modules/zod/v4/locales/hy.js init_define_KSQL_DOCS(); function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } function withDefiniteArticle(word) { if (!word) return ""; const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } var error20 = () => { const Sizable = { string: { unit: { one: "\u0576\u0577\u0561\u0576", many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, file: { unit: { one: "\u0562\u0561\u0575\u0569", many: "\u0562\u0561\u0575\u0569\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, array: { unit: { one: "\u057F\u0561\u0580\u0580", many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, set: { unit: { one: "\u057F\u0561\u0580\u0580", many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0574\u0578\u0582\u057F\u0584", email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", url: "URL", emoji: "\u0567\u0574\u0578\u057B\u056B", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", time: "ISO \u056A\u0561\u0574", duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; const TypeDictionary = { nan: "NaN", number: "\u0569\u056B\u057E", array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; } return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; if (_issue.format === "ends_with") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; if (_issue.format === "includes") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; if (_issue.format === "regex") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; case "unrecognized_keys": return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; case "invalid_union": return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; case "invalid_element": return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; default: return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; } }; }; function hy_default() { return { localeError: error20() }; } // node_modules/zod/v4/locales/id.js init_define_KSQL_DOCS(); var error21 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "alamat email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; } return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak valid: harus menyertakan "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak valid: harus sesuai pola ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; } case "not_multiple_of": return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak valid di ${issue2.origin}`; case "invalid_union": return "Input tidak valid"; case "invalid_element": return `Nilai tidak valid di ${issue2.origin}`; default: return `Input tidak valid`; } }; }; function id_default() { return { localeError: error21() }; } // node_modules/zod/v4/locales/is.js init_define_KSQL_DOCS(); var error22 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, set: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "gildi", email: "netfang", url: "vefsl\xF3\xF0", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dagsetning og t\xEDmi", date: "ISO dagsetning", time: "ISO t\xEDmi", duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", jwt: "JWT", template_literal: "gildi" }; const TypeDictionary = { nan: "NaN", number: "n\xFAmer", array: "fylki" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; } return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; } case "invalid_value": if (issue2.values.length === 1) return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; if (_issue.format === "regex") return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; case "unrecognized_keys": return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Rangur lykill \xED ${issue2.origin}`; case "invalid_union": return "Rangt gildi"; case "invalid_element": return `Rangt gildi \xED ${issue2.origin}`; default: return `Rangt gildi`; } }; }; function is_default() { return { localeError: error22() }; } // node_modules/zod/v4/locales/it.js init_define_KSQL_DOCS(); var error23 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "indirizzo email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "numero", array: "vettore" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; } return `Input non valido: atteso ${expected}, ricevuto ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`; if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`; if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; return `Input non valido: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; case "unrecognized_keys": return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chiave non valida in ${issue2.origin}`; case "invalid_union": return "Input non valido"; case "invalid_element": return `Valore non valido in ${issue2.origin}`; default: return `Input non valido`; } }; }; function it_default() { return { localeError: error23() }; } // node_modules/zod/v4/locales/ja.js init_define_KSQL_DOCS(); var error24 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; const TypeDictionary = { nan: "NaN", number: "\u6570\u5024", array: "\u914D\u5217" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; } return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; } case "invalid_value": if (issue2.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "too_big": { const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "too_small": { const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "unrecognized_keys": return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; case "invalid_union": return "\u7121\u52B9\u306A\u5165\u529B"; case "invalid_element": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; default: return `\u7121\u52B9\u306A\u5165\u529B`; } }; }; function ja_default() { return { localeError: error24() }; } // node_modules/zod/v4/locales/ka.js init_define_KSQL_DOCS(); var error25 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", url: "URL", emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", time: "\u10D3\u10E0\u10DD", duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; const TypeDictionary = { nan: "NaN", number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", string: "\u10D5\u10D4\u10DA\u10D8", boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; } return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; } if (_issue.format === "ends_with") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; if (_issue.format === "includes") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; if (_issue.format === "regex") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; case "unrecognized_keys": return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; case "invalid_union": return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; case "invalid_element": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; default: return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; } }; }; function ka_default() { return { localeError: error25() }; } // node_modules/zod/v4/locales/kh.js init_define_KSQL_DOCS(); // node_modules/zod/v4/locales/km.js init_define_KSQL_DOCS(); var error26 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; const TypeDictionary = { nan: "NaN", number: "\u179B\u17C1\u1781", array: "\u17A2\u17B6\u179A\u17C1 (Array)", null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; } return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; if (_issue.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; case "unrecognized_keys": return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; case "invalid_union": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; case "invalid_element": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; default: return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; } }; }; function km_default() { return { localeError: error26() }; } // node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } // node_modules/zod/v4/locales/ko.js init_define_KSQL_DOCS(); var error27 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; } return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; } case "invalid_value": if (issue2.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "too_big": { const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; } case "too_small": { const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) { return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; } return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; } if (_issue.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "unrecognized_keys": return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; case "invalid_union": return `\uC798\uBABB\uB41C \uC785\uB825`; case "invalid_element": return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; default: return `\uC798\uBABB\uB41C \uC785\uB825`; } }; }; function ko_default() { return { localeError: error27() }; } // node_modules/zod/v4/locales/lt.js init_define_KSQL_DOCS(); var capitalizeFirstCharacter = (text) => { return text.charAt(0).toUpperCase() + text.slice(1); }; function getUnitTypeFromNumber(number4) { const abs = Math.abs(number4); const last = abs % 10; const last2 = abs % 100; if (last2 >= 11 && last2 <= 19 || last === 0) return "many"; if (last === 1) return "one"; return "few"; } var error28 = () => { const Sizable = { string: { unit: { one: "simbolis", few: "simboliai", many: "simboli\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" }, bigger: { inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" } } }, file: { unit: { one: "baitas", few: "baitai", many: "bait\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne didesnis kaip", notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" }, bigger: { inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", notInclusive: "turi b\u016Bti didesnis kaip" } } }, array: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } }, set: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } } }; function getSizing(origin, unitType, inclusive, targetShouldBe) { const result = Sizable[origin] ?? null; if (result === null) return result; return { unit: result.unit[unitType], verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] }; } const FormatDictionary = { regex: "\u012Fvestis", email: "el. pa\u0161to adresas", url: "URL", emoji: "jaustukas", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO data ir laikas", date: "ISO data", time: "ISO laikas", duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", jwt: "JWT", template_literal: "\u012Fvestis" }; const TypeDictionary = { nan: "NaN", number: "skai\u010Dius", bigint: "sveikasis skai\u010Dius", string: "eilut\u0117", boolean: "login\u0117 reik\u0161m\u0117", undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", function: "funkcija", symbol: "simbolis", array: "masyvas", object: "objektas", null: "nulin\u0117 reik\u0161m\u0117" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; } return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; } case "invalid_value": if (issue2.values.length === 1) return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; case "too_big": { const origin = TypeDictionary[issue2.origin] ?? issue2.origin; const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); if (sizing?.verb) return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; } case "too_small": { const origin = TypeDictionary[issue2.origin] ?? issue2.origin; const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); if (sizing?.verb) return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; if (_issue.format === "includes") return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; if (_issue.format === "regex") return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; case "unrecognized_keys": return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Rastas klaidingas raktas"; case "invalid_union": return "Klaidinga \u012Fvestis"; case "invalid_element": { const origin = TypeDictionary[issue2.origin] ?? issue2.origin; return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; } default: return "Klaidinga \u012Fvestis"; } }; }; function lt_default() { return { localeError: error28() }; } // node_modules/zod/v4/locales/mk.js init_define_KSQL_DOCS(); var error29 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; const TypeDictionary = { nan: "NaN", number: "\u0431\u0440\u043E\u0458", array: "\u043D\u0438\u0437\u0430" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; } return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; case "invalid_union": return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; case "invalid_element": return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; default: return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; } }; }; function mk_default() { return { localeError: error29() }; } // node_modules/zod/v4/locales/ms.js init_define_KSQL_DOCS(); var error30 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "alamat e-mel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "nombor" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; } return `Input tidak sah: dijangka ${expected}, diterima ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak sah: mesti mengandungi "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; } case "not_multiple_of": return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak sah dalam ${issue2.origin}`; case "invalid_union": return "Input tidak sah"; case "invalid_element": return `Nilai tidak sah dalam ${issue2.origin}`; default: return `Input tidak sah`; } }; }; function ms_default() { return { localeError: error30() }; } // node_modules/zod/v4/locales/nl.js init_define_KSQL_DOCS(); var error31 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, set: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "invoer", email: "emailadres", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }; const TypeDictionary = { nan: "NaN", number: "getal" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; } return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; if (sizing) return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; if (sizing) { return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; } return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; } if (_issue.format === "ends_with") return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; if (_issue.format === "includes") return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; if (_issue.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; case "unrecognized_keys": return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ongeldige key in ${issue2.origin}`; case "invalid_union": return "Ongeldige invoer"; case "invalid_element": return `Ongeldige waarde in ${issue2.origin}`; default: return `Ongeldige invoer`; } }; }; function nl_default() { return { localeError: error31() }; } // node_modules/zod/v4/locales/no.js init_define_KSQL_DOCS(); var error32 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "e-postadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "tall", array: "liste" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; } return `Ugyldig input: forventet ${expected}, fikk ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8kkel i ${issue2.origin}`; case "invalid_union": return "Ugyldig input"; case "invalid_element": return `Ugyldig verdi i ${issue2.origin}`; default: return `Ugyldig input`; } }; }; function no_default() { return { localeError: error32() }; } // node_modules/zod/v4/locales/ota.js init_define_KSQL_DOCS(); var error33 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "giren", email: "epostag\xE2h", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" }; const TypeDictionary = { nan: "NaN", number: "numara", array: "saf", null: "gayb" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; } return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; } return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; if (_issue.format === "ends_with") return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; if (_issue.format === "includes") return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; if (_issue.format === "regex") return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; case "invalid_union": return "Giren tan\u0131namad\u0131."; case "invalid_element": return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; default: return `K\u0131ymet tan\u0131namad\u0131.`; } }; }; function ota_default() { return { localeError: error33() }; } // node_modules/zod/v4/locales/ps.js init_define_KSQL_DOCS(); var error34 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; const TypeDictionary = { nan: "NaN", number: "\u0639\u062F\u062F", array: "\u0627\u0631\u06D0" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; } return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; } case "invalid_value": if (issue2.values.length === 1) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; } return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; } if (_issue.format === "ends_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; } if (_issue.format === "includes") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; } if (_issue.format === "regex") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; } return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; } case "not_multiple_of": return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; case "unrecognized_keys": return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; case "invalid_union": return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; case "invalid_element": return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; default: return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; } }; }; function ps_default() { return { localeError: error34() }; } // node_modules/zod/v4/locales/pl.js init_define_KSQL_DOCS(); var error35 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "wyra\u017Cenie", email: "adres email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" }; const TypeDictionary = { nan: "NaN", number: "liczba", array: "tablica" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; } return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; if (_issue.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; if (_issue.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; case "unrecognized_keys": return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nieprawid\u0142owy klucz w ${issue2.origin}`; case "invalid_union": return "Nieprawid\u0142owe dane wej\u015Bciowe"; case "invalid_element": return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; default: return `Nieprawid\u0142owe dane wej\u015Bciowe`; } }; }; function pl_default() { return { localeError: error35() }; } // node_modules/zod/v4/locales/pt.js init_define_KSQL_DOCS(); var error36 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN", number: "n\xFAmero", null: "nulo" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; } return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chave inv\xE1lida em ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido em ${issue2.origin}`; default: return `Campo inv\xE1lido`; } }; }; function pt_default() { return { localeError: error36() }; } // node_modules/zod/v4/locales/ro.js init_define_KSQL_DOCS(); var error37 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, array: { unit: "elemente", verb: "s\u0103 aib\u0103" }, set: { unit: "elemente", verb: "s\u0103 aib\u0103" }, map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "intrare", email: "adres\u0103 de email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "dat\u0103 \u0219i or\u0103 ISO", date: "dat\u0103 ISO", time: "or\u0103 ISO", duration: "durat\u0103 ISO", ipv4: "adres\u0103 IPv4", ipv6: "adres\u0103 IPv6", mac: "adres\u0103 MAC", cidrv4: "interval IPv4", cidrv6: "interval IPv6", base64: "\u0219ir codat base64", base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", jwt: "JWT", template_literal: "intrare" }; const TypeDictionary = { nan: "NaN", string: "\u0219ir", number: "num\u0103r", boolean: "boolean", function: "func\u021Bie", array: "matrice", object: "obiect", undefined: "nedefinit", symbol: "simbol", bigint: "num\u0103r mare", void: "void", never: "never", map: "hart\u0103", set: "set" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`; return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemente"}`; return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`; return `Format invalid: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`; case "unrecognized_keys": return `Chei nerecunoscute: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cheie invalid\u0103 \xEEn ${issue2.origin}`; case "invalid_union": return "Intrare invalid\u0103"; case "invalid_element": return `Valoare invalid\u0103 \xEEn ${issue2.origin}`; default: return `Intrare invalid\u0103`; } }; }; function ro_default() { return { localeError: error37() }; } // node_modules/zod/v4/locales/ru.js init_define_KSQL_DOCS(); function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error38 = () => { const Sizable = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0441\u0438\u0432" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; } return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; case "invalid_element": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; default: return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; } }; }; function ru_default() { return { localeError: error38() }; } // node_modules/zod/v4/locales/sl.js init_define_KSQL_DOCS(); var error39 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "vnos", email: "e-po\u0161tni naslov", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" }; const TypeDictionary = { nan: "NaN", number: "\u0161tevilo", array: "tabela" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; } return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; if (_issue.format === "includes") return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; if (_issue.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; case "unrecognized_keys": return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neveljaven klju\u010D v ${issue2.origin}`; case "invalid_union": return "Neveljaven vnos"; case "invalid_element": return `Neveljavna vrednost v ${issue2.origin}`; default: return "Neveljaven vnos"; } }; }; function sl_default() { return { localeError: error39() }; } // node_modules/zod/v4/locales/sv.js init_define_KSQL_DOCS(); var error40 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "regulj\xE4rt uttryck", email: "e-postadress", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }; const TypeDictionary = { nan: "NaN", number: "antal", array: "lista" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; } return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; } return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; if (_issue.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; case "invalid_union": return "Ogiltig input"; case "invalid_element": return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; default: return `Ogiltig input`; } }; }; function sv_default() { return { localeError: error40() }; } // node_modules/zod/v4/locales/ta.js init_define_KSQL_DOCS(); var error41 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "\u0B8E\u0BA3\u0BCD", array: "\u0B85\u0BA3\u0BBF", null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; } return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; case "unrecognized_keys": return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; case "invalid_union": return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; case "invalid_element": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; default: return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; } }; }; function ta_default() { return { localeError: error41() }; } // node_modules/zod/v4/locales/th.js init_define_KSQL_DOCS(); var error42 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; const TypeDictionary = { nan: "NaN", number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; } return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; if (_issue.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; case "unrecognized_keys": return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; case "invalid_union": return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; case "invalid_element": return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; default: return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; } }; }; function th_default() { return { localeError: error42() }; } // node_modules/zod/v4/locales/tr.js init_define_KSQL_DOCS(); var error43 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "girdi", email: "e-posta adresi", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; } return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; if (_issue.format === "ends_with") return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; if (_issue.format === "includes") return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; if (_issue.format === "regex") return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; case "invalid_union": return "Ge\xE7ersiz de\u011Fer"; case "invalid_element": return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; default: return `Ge\xE7ersiz de\u011Fer`; } }; }; function tr_default() { return { localeError: error43() }; } // node_modules/zod/v4/locales/ua.js init_define_KSQL_DOCS(); // node_modules/zod/v4/locales/uk.js init_define_KSQL_DOCS(); var error44 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0438\u0432" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; } return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; case "invalid_element": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; default: return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; } }; }; function uk_default() { return { localeError: error44() }; } // node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } // node_modules/zod/v4/locales/ur.js init_define_KSQL_DOCS(); var error45 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; const TypeDictionary = { nan: "NaN", number: "\u0646\u0645\u0628\u0631", array: "\u0622\u0631\u06D2", null: "\u0646\u0644" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; } return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; } case "invalid_value": if (issue2.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; } return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; } if (_issue.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; case "unrecognized_keys": return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; case "invalid_union": return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; case "invalid_element": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; default: return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; } }; }; function ur_default() { return { localeError: error45() }; } // node_modules/zod/v4/locales/uz.js init_define_KSQL_DOCS(); var error46 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, array: { unit: "element", verb: "bo\u2018lishi kerak" }, set: { unit: "element", verb: "bo\u2018lishi kerak" }, map: { unit: "yozuv", verb: "bo\u2018lishi kerak" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "kirish", email: "elektron pochta manzili", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO sana va vaqti", date: "ISO sana", time: "ISO vaqt", duration: "ISO davomiylik", ipv4: "IPv4 manzil", ipv6: "IPv6 manzil", mac: "MAC manzil", cidrv4: "IPv4 diapazon", cidrv6: "IPv6 diapazon", base64: "base64 kodlangan satr", base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", jwt: "JWT", template_literal: "kirish" }; const TypeDictionary = { nan: "NaN", number: "raqam", array: "massiv" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; } return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; } return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; if (_issue.format === "ends_with") return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; if (_issue.format === "includes") return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; if (_issue.format === "regex") return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; case "unrecognized_keys": return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; case "invalid_union": return "Noto\u2018g\u2018ri kirish"; case "invalid_element": return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; default: return `Noto\u2018g\u2018ri kirish`; } }; }; function uz_default() { return { localeError: error46() }; } // node_modules/zod/v4/locales/vi.js init_define_KSQL_DOCS(); var error47 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; const TypeDictionary = { nan: "NaN", number: "s\u1ED1", array: "m\u1EA3ng" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; } return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; if (_issue.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; if (_issue.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; } case "not_multiple_of": return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; case "unrecognized_keys": return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; case "invalid_union": return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; case "invalid_element": return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; default: return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; } }; }; function vi_default() { return { localeError: error47() }; } // node_modules/zod/v4/locales/zh-CN.js init_define_KSQL_DOCS(); var error48 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" }; const TypeDictionary = { nan: "NaN", number: "\u6570\u5B57", array: "\u6570\u7EC4", null: "\u7A7A\u503C(null)" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; } return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; if (_issue.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; if (_issue.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; case "unrecognized_keys": return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; case "invalid_union": return "\u65E0\u6548\u8F93\u5165"; case "invalid_element": return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; default: return `\u65E0\u6548\u8F93\u5165`; } }; }; function zh_CN_default() { return { localeError: error48() }; } // node_modules/zod/v4/locales/zh-TW.js init_define_KSQL_DOCS(); var error49 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; } return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; } if (_issue.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; if (_issue.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; case "unrecognized_keys": return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; case "invalid_union": return "\u7121\u6548\u7684\u8F38\u5165\u503C"; case "invalid_element": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; default: return `\u7121\u6548\u7684\u8F38\u5165\u503C`; } }; }; function zh_TW_default() { return { localeError: error49() }; } // node_modules/zod/v4/locales/yo.js init_define_KSQL_DOCS(); var error50 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, set: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\xE0k\xF3k\xF2 ISO", date: "\u1ECDj\u1ECD\u0301 ISO", time: "\xE0k\xF3k\xF2 ISO", duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; const TypeDictionary = { nan: "NaN", number: "n\u1ECD\u0301mb\xE0", array: "akop\u1ECD" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; } return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; if (_issue.format === "regex") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; case "unrecognized_keys": return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; case "invalid_union": return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; case "invalid_element": return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; default: return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; } }; }; function yo_default() { return { localeError: error50() }; } // node_modules/zod/v4/core/registries.js init_define_KSQL_DOCS(); var _a2; var $output = /* @__PURE__ */ Symbol("ZodOutput"); var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { const meta3 = _meta[0]; this._map.set(schema, meta3); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.set(meta3.id, schema); } return this; } clear() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); return this; } remove(schema) { const meta3 = this._map.get(schema); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.delete(meta3.id); } this._map.delete(schema); return this; } get(schema) { const p = schema._zod.parent; if (p) { const pm = { ...this.get(p) ?? {} }; delete pm.id; const f = { ...pm, ...this._map.get(schema) }; return Object.keys(f).length ? f : void 0; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } }; function registry() { return new $ZodRegistry(); } (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; // node_modules/zod/v4/core/api.js init_define_KSQL_DOCS(); // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { return new Class2({ type: "string", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { return new Class2({ type: "string", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { return new Class2({ type: "string", format: "email", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _guid(Class2, params) { return new Class2({ type: "string", format: "guid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuid(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv4(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv6(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv7(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _url(Class2, params) { return new Class2({ type: "string", format: "url", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _emoji2(Class2, params) { return new Class2({ type: "string", format: "emoji", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nanoid(Class2, params) { return new Class2({ type: "string", format: "nanoid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cuid(Class2, params) { return new Class2({ type: "string", format: "cuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cuid2(Class2, params) { return new Class2({ type: "string", format: "cuid2", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ulid(Class2, params) { return new Class2({ type: "string", format: "ulid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _xid(Class2, params) { return new Class2({ type: "string", format: "xid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ksuid(Class2, params) { return new Class2({ type: "string", format: "ksuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ipv4(Class2, params) { return new Class2({ type: "string", format: "ipv4", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ipv6(Class2, params) { return new Class2({ type: "string", format: "ipv6", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _mac(Class2, params) { return new Class2({ type: "string", format: "mac", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cidrv4(Class2, params) { return new Class2({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cidrv6(Class2, params) { return new Class2({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _base64(Class2, params) { return new Class2({ type: "string", format: "base64", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _base64url(Class2, params) { return new Class2({ type: "string", format: "base64url", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _e164(Class2, params) { return new Class2({ type: "string", format: "e164", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", format: "jwt", check: "string_format", abort: false, ...normalizeParams(params) }); } var TimePrecision = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 }; // @__NO_SIDE_EFFECTS__ function _isoDateTime(Class2, params) { return new Class2({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoDate(Class2, params) { return new Class2({ type: "string", format: "date", check: "string_format", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoTime(Class2, params) { return new Class2({ type: "string", format: "time", check: "string_format", precision: null, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoDuration(Class2, params) { return new Class2({ type: "string", format: "duration", check: "string_format", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { return new Class2({ type: "number", checks: [], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { return new Class2({ type: "number", coerce: true, checks: [], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _float32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "float32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _float64(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "float64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "int32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uint32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "uint32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _boolean(Class2, params) { return new Class2({ type: "boolean", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedBoolean(Class2, params) { return new Class2({ type: "boolean", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _bigint(Class2, params) { return new Class2({ type: "bigint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedBigint(Class2, params) { return new Class2({ type: "bigint", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int64(Class2, params) { return new Class2({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uint64(Class2, params) { return new Class2({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _symbol(Class2, params) { return new Class2({ type: "symbol", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _undefined2(Class2, params) { return new Class2({ type: "undefined", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _null2(Class2, params) { return new Class2({ type: "null", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _any(Class2) { return new Class2({ type: "any" }); } // @__NO_SIDE_EFFECTS__ function _unknown(Class2) { return new Class2({ type: "unknown" }); } // @__NO_SIDE_EFFECTS__ function _never(Class2, params) { return new Class2({ type: "never", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _void(Class2, params) { return new Class2({ type: "void", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _date(Class2, params) { return new Class2({ type: "date", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedDate(Class2, params) { return new Class2({ type: "date", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nan(Class2, params) { return new Class2({ type: "nan", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _lt(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _lte(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _positive(params) { return /* @__PURE__ */ _gt(0, params); } // @__NO_SIDE_EFFECTS__ function _negative(params) { return /* @__PURE__ */ _lt(0, params); } // @__NO_SIDE_EFFECTS__ function _nonpositive(params) { return /* @__PURE__ */ _lte(0, params); } // @__NO_SIDE_EFFECTS__ function _nonnegative(params) { return /* @__PURE__ */ _gte(0, params); } // @__NO_SIDE_EFFECTS__ function _multipleOf(value, params) { return new $ZodCheckMultipleOf({ check: "multiple_of", ...normalizeParams(params), value }); } // @__NO_SIDE_EFFECTS__ function _maxSize(maximum, params) { return new $ZodCheckMaxSize({ check: "max_size", ...normalizeParams(params), maximum }); } // @__NO_SIDE_EFFECTS__ function _minSize(minimum, params) { return new $ZodCheckMinSize({ check: "min_size", ...normalizeParams(params), minimum }); } // @__NO_SIDE_EFFECTS__ function _size(size, params) { return new $ZodCheckSizeEquals({ check: "size_equals", ...normalizeParams(params), size }); } // @__NO_SIDE_EFFECTS__ function _maxLength(maximum, params) { const ch = new $ZodCheckMaxLength({ check: "max_length", ...normalizeParams(params), maximum }); return ch; } // @__NO_SIDE_EFFECTS__ function _minLength(minimum, params) { return new $ZodCheckMinLength({ check: "min_length", ...normalizeParams(params), minimum }); } // @__NO_SIDE_EFFECTS__ function _length(length, params) { return new $ZodCheckLengthEquals({ check: "length_equals", ...normalizeParams(params), length }); } // @__NO_SIDE_EFFECTS__ function _regex(pattern, params) { return new $ZodCheckRegex({ check: "string_format", format: "regex", ...normalizeParams(params), pattern }); } // @__NO_SIDE_EFFECTS__ function _lowercase(params) { return new $ZodCheckLowerCase({ check: "string_format", format: "lowercase", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uppercase(params) { return new $ZodCheckUpperCase({ check: "string_format", format: "uppercase", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _includes(includes, params) { return new $ZodCheckIncludes({ check: "string_format", format: "includes", ...normalizeParams(params), includes }); } // @__NO_SIDE_EFFECTS__ function _startsWith(prefix, params) { return new $ZodCheckStartsWith({ check: "string_format", format: "starts_with", ...normalizeParams(params), prefix }); } // @__NO_SIDE_EFFECTS__ function _endsWith(suffix, params) { return new $ZodCheckEndsWith({ check: "string_format", format: "ends_with", ...normalizeParams(params), suffix }); } // @__NO_SIDE_EFFECTS__ function _property(property, schema, params) { return new $ZodCheckProperty({ check: "property", property, schema, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _mime(types, params) { return new $ZodCheckMimeType({ check: "mime_type", mime: types, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _overwrite(tx) { return new $ZodCheckOverwrite({ check: "overwrite", tx }); } // @__NO_SIDE_EFFECTS__ function _normalize(form) { return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { return /* @__PURE__ */ _overwrite((input) => input.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { return /* @__PURE__ */ _overwrite((input) => slugify(input)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { return new Class2({ type: "array", element, // get element() { // return element; // }, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _union(Class2, options, params) { return new Class2({ type: "union", options, ...normalizeParams(params) }); } function _xor(Class2, options, params) { return new Class2({ type: "union", options, inclusive: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _discriminatedUnion(Class2, discriminator, options, params) { return new Class2({ type: "union", options, discriminator, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _intersection(Class2, left, right) { return new Class2({ type: "intersection", left, right }); } // @__NO_SIDE_EFFECTS__ function _tuple(Class2, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class2({ type: "tuple", items, rest, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _record(Class2, keyType, valueType, params) { return new Class2({ type: "record", keyType, valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _map(Class2, keyType, valueType, params) { return new Class2({ type: "map", keyType, valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _set(Class2, valueType, params) { return new Class2({ type: "set", valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _enum(Class2, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new Class2({ type: "enum", entries, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nativeEnum(Class2, entries, params) { return new Class2({ type: "enum", entries, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _literal(Class2, value, params) { return new Class2({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _file(Class2, params) { return new Class2({ type: "file", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _transform(Class2, fn) { return new Class2({ type: "transform", transform: fn }); } // @__NO_SIDE_EFFECTS__ function _optional(Class2, innerType) { return new Class2({ type: "optional", innerType }); } // @__NO_SIDE_EFFECTS__ function _nullable(Class2, innerType) { return new Class2({ type: "nullable", innerType }); } // @__NO_SIDE_EFFECTS__ function _default(Class2, innerType, defaultValue) { return new Class2({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); } }); } // @__NO_SIDE_EFFECTS__ function _nonoptional(Class2, innerType, params) { return new Class2({ type: "nonoptional", innerType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _success(Class2, innerType) { return new Class2({ type: "success", innerType }); } // @__NO_SIDE_EFFECTS__ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } // @__NO_SIDE_EFFECTS__ function _pipe(Class2, in_, out) { return new Class2({ type: "pipe", in: in_, out }); } // @__NO_SIDE_EFFECTS__ function _readonly(Class2, innerType) { return new Class2({ type: "readonly", innerType }); } // @__NO_SIDE_EFFECTS__ function _templateLiteral(Class2, parts, params) { return new Class2({ type: "template_literal", parts, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _lazy(Class2, getter) { return new Class2({ type: "lazy", getter }); } // @__NO_SIDE_EFFECTS__ function _promise(Class2, innerType) { return new Class2({ type: "promise", innerType }); } // @__NO_SIDE_EFFECTS__ function _custom(Class2, fn, _params) { const norm = normalizeParams(_params); norm.abort ?? (norm.abort = true); const schema = new Class2({ type: "custom", check: "custom", fn, ...norm }); return schema; } // @__NO_SIDE_EFFECTS__ function _refine(Class2, fn, _params) { const schema = new Class2({ type: "custom", check: "custom", fn, ...normalizeParams(_params) }); return schema; } // @__NO_SIDE_EFFECTS__ function _superRefine(fn, params) { const ch = /* @__PURE__ */ _check((payload) => { payload.addIssue = (issue2) => { if (typeof issue2 === "string") { payload.issues.push(issue(issue2, payload.value, ch._zod.def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); } }; return fn(payload.value, payload); }, params); return ch; } // @__NO_SIDE_EFFECTS__ function _check(fn, params) { const ch = new $ZodCheck({ check: "custom", ...normalizeParams(params) }); ch._zod.check = fn; return ch; } // @__NO_SIDE_EFFECTS__ function describe(description) { const ch = new $ZodCheck({ check: "describe" }); ch._zod.onattach = [ (inst) => { const existing = globalRegistry.get(inst) ?? {}; globalRegistry.add(inst, { ...existing, description }); } ]; ch._zod.check = () => { }; return ch; } // @__NO_SIDE_EFFECTS__ function meta(metadata) { const ch = new $ZodCheck({ check: "meta" }); ch._zod.onattach = [ (inst) => { const existing = globalRegistry.get(inst) ?? {}; globalRegistry.add(inst, { ...existing, ...metadata }); } ]; ch._zod.check = () => { }; return ch; } // @__NO_SIDE_EFFECTS__ function _stringbool(Classes, _params) { const params = normalizeParams(_params); let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; if (params.case !== "sensitive") { truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); } const truthySet = new Set(truthyArray); const falsySet = new Set(falsyArray); const _Codec = Classes.Codec ?? $ZodCodec; const _Boolean = Classes.Boolean ?? $ZodBoolean; const _String = Classes.String ?? $ZodString; const stringSchema = new _String({ type: "string", error: params.error }); const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); const codec2 = new _Codec({ type: "pipe", in: stringSchema, out: booleanSchema, transform: ((input, payload) => { let data = input; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { return true; } else if (falsySet.has(data)) { return false; } else { payload.issues.push({ code: "invalid_value", expected: "stringbool", values: [...truthySet, ...falsySet], input: payload.value, inst: codec2, continue: false }); return {}; } }), reverseTransform: ((input, _payload) => { if (input === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; } }), error: params.error }); return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { ...normalizeParams(_params), check: "string_format", type: "string", format, fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), ...params }; if (fnOrRegex instanceof RegExp) { def.pattern = fnOrRegex; } const inst = new Class2(def); return inst; } // node_modules/zod/v4/core/to-json-schema.js init_define_KSQL_DOCS(); function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") target = "draft-04"; if (target === "draft-7") target = "draft-07"; return { processors: params.processors ?? {}, metadataRegistry: params?.metadata ?? globalRegistry, target, unrepresentable: params?.unrepresentable ?? "throw", override: params?.override ?? (() => { }), io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", external: params?.external ?? void 0 }; } function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a3; const def = schema._zod.def; const seen = ctx.seen.get(schema); if (seen) { seen.count++; const isCycle = _params.schemaPath.includes(schema); if (isCycle) { seen.cycle = _params.path; } return seen.schema; } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; } else { const params = { ..._params, schemaPath: [..._params.schemaPath, schema], path: _params.path }; if (schema._zod.processJSONSchema) { schema._zod.processJSONSchema(ctx, result.schema, params); } else { const _json = result.schema; const processor = ctx.processors[def.type]; if (!processor) { throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); } processor(schema, ctx, _json, params); } const parent = schema._zod.parent; if (parent) { if (!result.ref) result.ref = parent; process2(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) Object.assign(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; } if (ctx.io === "input" && "_prefault" in result.schema) (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault); delete result.schema._prefault; const _result = ctx.seen.get(schema); return _result.schema; } function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; if (id) { const existing = idToSchema.get(id); if (existing && existing !== entry[0]) { throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); } idToSchema.set(id, entry[0]); } } const makeURI = (entry) => { const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; if (ctx.external) { const externalId = ctx.external.registry.get(entry[0])?.id; const uriGenerator = ctx.external.uri ?? ((id2) => id2); if (externalId) { return { ref: uriGenerator(externalId) }; } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root) { return { ref: "#" }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; return { defId, ref: defUriPrefix + defId }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = { ...seen.schema }; if (defId) seen.defId = defId; const schema2 = seen.schema; for (const key in schema2) { delete schema2[key]; } schema2.$ref = ref; }; if (ctx.cycles === "throw") { for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (seen.cycle) { throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); } } } for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (schema === entry[0]) { extractToDef(entry); continue; } if (ctx.external) { const ext = ctx.external.registry.get(entry[0])?.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } const id = ctx.metadataRegistry.get(entry[0])?.id; if (id) { extractToDef(entry); continue; } if (seen.cycle) { extractToDef(entry); continue; } if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); continue; } } } } function finalize(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const flattenRef = (zodSchema) => { const seen = ctx.seen.get(zodSchema); if (seen.ref === null) return; const schema2 = seen.def ?? seen.schema; const _cached = { ...schema2 }; const ref = seen.ref; seen.ref = null; if (ref) { flattenRef(ref); const refSeen = ctx.seen.get(ref); const refSchema = refSeen.schema; if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { Object.assign(schema2, refSchema); } Object.assign(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (!(key in _cached)) { delete schema2[key]; } } } if (refSchema.$ref && refSeen.def) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { delete schema2[key]; } } } } const parent = zodSchema._zod.parent; if (parent && parent !== ref) { flattenRef(parent); const parentSeen = ctx.seen.get(parent); if (parentSeen?.schema.$ref) { schema2.$ref = parentSeen.schema.$ref; if (parentSeen.def) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { delete schema2[key]; } } } } } ctx.override({ zodSchema, jsonSchema: schema2, path: seen.path ?? [] }); }; for (const entry of [...ctx.seen.entries()].reverse()) { flattenRef(entry[0]); } const result = {}; if (ctx.target === "draft-2020-12") { result.$schema = "https://json-schema.org/draft/2020-12/schema"; } else if (ctx.target === "draft-07") { result.$schema = "http://json-schema.org/draft-07/schema#"; } else if (ctx.target === "draft-04") { result.$schema = "http://json-schema.org/draft-04/schema#"; } else if (ctx.target === "openapi-3.0") { } else { } if (ctx.external?.uri) { const id = ctx.external.registry.get(schema)?.id; if (!id) throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } Object.assign(result, root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (seen.def && seen.defId) { if (seen.def.id === seen.defId) delete seen.def.id; defs[seen.defId] = seen.def; } } if (ctx.external) { } else { if (Object.keys(defs).length > 0) { if (ctx.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { const finalized = JSON.parse(JSON.stringify(result)); Object.defineProperty(finalized, "~standard", { value: { ...schema["~standard"], jsonSchema: { input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) } }, enumerable: false, writable: false }); return finalized; } catch (_err) { throw new Error("Error converting schema to JSON."); } } function isTransforming(_schema, _ctx) { const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; if (ctx.seen.has(_schema)) return false; ctx.seen.add(_schema); const def = _schema._zod.def; if (def.type === "transform") return true; if (def.type === "array") return isTransforming(def.element, ctx); if (def.type === "set") return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } if (def.type === "record" || def.type === "map") { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } if (def.type === "pipe") { if (_schema._zod.traits.has("$ZodCodec")) return true; return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } if (def.type === "object") { for (const key in def.shape) { if (isTransforming(def.shape[key], ctx)) return true; } return false; } if (def.type === "union") { for (const option of def.options) { if (isTransforming(option, ctx)) return true; } return false; } if (def.type === "tuple") { for (const item of def.items) { if (isTransforming(item, ctx)) return true; } if (def.rest && isTransforming(def.rest, ctx)) return true; return false; } return false; } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); process2(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); process2(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; // node_modules/zod/v4/core/json-schema-processors.js init_define_KSQL_DOCS(); var formatMap = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" // do not set }; var stringProcessor = (schema, ctx, _json, _params) => { const json2 = _json; json2.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; if (typeof minimum === "number") json2.minLength = minimum; if (typeof maximum === "number") json2.maxLength = maximum; if (format) { json2.format = formatMap[format] ?? format; if (json2.format === "") delete json2.format; if (format === "time") { delete json2.format; } } if (contentEncoding) json2.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json2.pattern = regexes[0].source; else if (regexes.length > 1) { json2.allOf = [ ...regexes.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) ]; } } }; var numberProcessor = (schema, ctx, _json, _params) => { const json2 = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json2.type = "integer"; else json2.type = "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; if (exMin) { if (legacy) { json2.minimum = exclusiveMinimum; json2.exclusiveMinimum = true; } else { json2.exclusiveMinimum = exclusiveMinimum; } } else if (typeof minimum === "number") { json2.minimum = minimum; } if (exMax) { if (legacy) { json2.maximum = exclusiveMaximum; json2.exclusiveMaximum = true; } else { json2.exclusiveMaximum = exclusiveMaximum; } } else if (typeof maximum === "number") { json2.maximum = maximum; } if (typeof multipleOf === "number") json2.multipleOf = multipleOf; }; var booleanProcessor = (_schema, _ctx, json2, _params) => { json2.type = "boolean"; }; var bigintProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("BigInt cannot be represented in JSON Schema"); } }; var symbolProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Symbols cannot be represented in JSON Schema"); } }; var nullProcessor = (_schema, ctx, json2, _params) => { if (ctx.target === "openapi-3.0") { json2.type = "string"; json2.nullable = true; json2.enum = [null]; } else { json2.type = "null"; } }; var undefinedProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Undefined cannot be represented in JSON Schema"); } }; var voidProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Void cannot be represented in JSON Schema"); } }; var neverProcessor = (_schema, _ctx, json2, _params) => { json2.not = {}; }; var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; var dateProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Date cannot be represented in JSON Schema"); } }; var enumProcessor = (schema, _ctx, json2, _params) => { const def = schema._zod.def; const values = getEnumValues(def.entries); if (values.every((v) => typeof v === "number")) json2.type = "number"; if (values.every((v) => typeof v === "string")) json2.type = "string"; json2.enum = values; }; var literalProcessor = (schema, ctx, json2, _params) => { const def = schema._zod.def; const vals = []; for (const val of def.values) { if (val === void 0) { if (ctx.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } else { } } else if (typeof val === "bigint") { if (ctx.unrepresentable === "throw") { throw new Error("BigInt literals cannot be represented in JSON Schema"); } else { vals.push(Number(val)); } } else { vals.push(val); } } if (vals.length === 0) { } else if (vals.length === 1) { const val = vals[0]; json2.type = val === null ? "null" : typeof val; if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { json2.enum = [val]; } else { json2.const = val; } } else { if (vals.every((v) => typeof v === "number")) json2.type = "number"; if (vals.every((v) => typeof v === "string")) json2.type = "string"; if (vals.every((v) => typeof v === "boolean")) json2.type = "boolean"; if (vals.every((v) => v === null)) json2.type = "null"; json2.enum = vals; } }; var nanProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("NaN cannot be represented in JSON Schema"); } }; var templateLiteralProcessor = (schema, _ctx, json2, _params) => { const _json = json2; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); _json.type = "string"; _json.pattern = pattern.source; }; var fileProcessor = (schema, _ctx, json2, _params) => { const _json = json2; const file2 = { type: "string", format: "binary", contentEncoding: "binary" }; const { minimum, maximum, mime } = schema._zod.bag; if (minimum !== void 0) file2.minLength = minimum; if (maximum !== void 0) file2.maxLength = maximum; if (mime) { if (mime.length === 1) { file2.contentMediaType = mime[0]; Object.assign(_json, file2); } else { Object.assign(_json, file2); _json.anyOf = mime.map((m) => ({ contentMediaType: m })); } } else { Object.assign(_json, file2); } }; var successProcessor = (_schema, _ctx, json2, _params) => { json2.type = "boolean"; }; var customProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Custom types cannot be represented in JSON Schema"); } }; var functionProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Function types cannot be represented in JSON Schema"); } }; var transformProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Transforms cannot be represented in JSON Schema"); } }; var mapProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Map cannot be represented in JSON Schema"); } }; var setProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Set cannot be represented in JSON Schema"); } }; var arrayProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json2.minItems = minimum; if (typeof maximum === "number") json2.maxItems = maximum; json2.type = "array"; json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; var objectProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; json2.type = "object"; json2.properties = {}; const shape = def.shape; for (const key in shape) { json2.properties[key] = process2(shape[key], ctx, { ...params, path: [...params.path, "properties", key] }); } const allKeys = new Set(Object.keys(shape)); const requiredKeys = new Set([...allKeys].filter((key) => { const v = def.shape[key]._zod; if (ctx.io === "input") { return v.optin === void 0; } else { return v.optout === void 0; } })); if (requiredKeys.size > 0) { json2.required = Array.from(requiredKeys); } if (def.catchall?._zod.def.type === "never") { json2.additionalProperties = false; } else if (!def.catchall) { if (ctx.io === "output") json2.additionalProperties = false; } else if (def.catchall) { json2.additionalProperties = process2(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } }; var unionProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; const options = def.options.map((x, i) => process2(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); if (isExclusive) { json2.oneOf = options; } else { json2.anyOf = options; } }; var intersectionProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; const a = process2(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); const b = process2(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; const allOf = [ ...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b] ]; json2.allOf = allOf; }; var tupleProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; json2.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; const prefixItems = def.items.map((x, i) => process2(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); const rest = def.rest ? process2(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; if (ctx.target === "draft-2020-12") { json2.prefixItems = prefixItems; if (rest) { json2.items = rest; } } else if (ctx.target === "openapi-3.0") { json2.items = { anyOf: prefixItems }; if (rest) { json2.items.anyOf.push(rest); } json2.minItems = prefixItems.length; if (!rest) { json2.maxItems = prefixItems.length; } } else { json2.items = prefixItems; if (rest) { json2.additionalItems = rest; } } const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json2.minItems = minimum; if (typeof maximum === "number") json2.maxItems = maximum; }; var recordProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; json2.type = "object"; const keyType = def.keyType; const keyBag = keyType._zod.bag; const patterns = keyBag?.patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { const valueSchema = process2(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json2.patternProperties = {}; for (const pattern of patterns) { json2.patternProperties[pattern.source] = valueSchema; } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { json2.propertyNames = process2(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); } json2.additionalProperties = process2(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; if (keyValues) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { json2.required = validKeyValues; } } }; var nullableProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; const inner = process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; json2.nullable = true; } else { json2.anyOf = [inner, { type: "null" }]; } }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var defaultProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json2.default = JSON.parse(JSON.stringify(def.defaultValue)); }; var prefaultProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; if (ctx.io === "input") json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); }; var catchProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { throw new Error("Dynamic catch values are not supported in JSON Schema"); } json2.default = catchValue; }; var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; process2(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json2.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; process2(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var allProcessors = { string: stringProcessor, number: numberProcessor, boolean: booleanProcessor, bigint: bigintProcessor, symbol: symbolProcessor, null: nullProcessor, undefined: undefinedProcessor, void: voidProcessor, never: neverProcessor, any: anyProcessor, unknown: unknownProcessor, date: dateProcessor, enum: enumProcessor, literal: literalProcessor, nan: nanProcessor, template_literal: templateLiteralProcessor, file: fileProcessor, success: successProcessor, custom: customProcessor, function: functionProcessor, transform: transformProcessor, map: mapProcessor, set: setProcessor, array: arrayProcessor, object: objectProcessor, union: unionProcessor, intersection: intersectionProcessor, tuple: tupleProcessor, record: recordProcessor, nullable: nullableProcessor, nonoptional: nonoptionalProcessor, default: defaultProcessor, prefault: prefaultProcessor, catch: catchProcessor, pipe: pipeProcessor, readonly: readonlyProcessor, promise: promiseProcessor, optional: optionalProcessor, lazy: lazyProcessor }; function toJSONSchema(input, params) { if ("_idmap" in input) { const registry2 = input; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; process2(schema, ctx2); } const schemas = {}; const external = { registry: registry2, uri: params?.uri, defs }; ctx2.external = external; for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); schemas[key] = finalize(ctx2, schema); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs }; } return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); process2(input, ctx); extractDefs(ctx, input); return finalize(ctx, input); } // node_modules/zod/v4/core/json-schema-generator.js init_define_KSQL_DOCS(); var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { return this.ctx.metadataRegistry; } /** @deprecated Access via ctx instead */ get target() { return this.ctx.target; } /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; } /** @deprecated Access via ctx instead */ get override() { return this.ctx.override; } /** @deprecated Access via ctx instead */ get io() { return this.ctx.io; } /** @deprecated Access via ctx instead */ get counter() { return this.ctx.counter; } set counter(value) { this.ctx.counter = value; } /** @deprecated Access via ctx instead */ get seen() { return this.ctx.seen; } constructor(params) { let normalizedTarget = params?.target ?? "draft-2020-12"; if (normalizedTarget === "draft-4") normalizedTarget = "draft-04"; if (normalizedTarget === "draft-7") normalizedTarget = "draft-07"; this.ctx = initializeContext({ processors: allProcessors, target: normalizedTarget, ...params?.metadata && { metadata: params.metadata }, ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, ...params?.override && { override: params.override }, ...params?.io && { io: params.io } }); } /** * Process a schema to prepare it for JSON Schema generation. * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { return process2(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. * Must call process() first. */ emit(schema, _params) { if (_params) { if (_params.cycles) this.ctx.cycles = _params.cycles; if (_params.reused) this.ctx.reused = _params.reused; if (_params.external) this.ctx.external = _params.external; } extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; return plainResult; } }; // node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; init_define_KSQL_DOCS(); // node_modules/zod/v4/mini/parse.js init_define_KSQL_DOCS(); // node_modules/zod/v4/mini/schemas.js init_define_KSQL_DOCS(); var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => { if (!inst._zod) throw new Error("Uninitialized schema in ZodMiniType."); $ZodType.init(inst, def); inst.def = def; inst.type = def.type; inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse(inst, data, params); inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); inst.check = (...checks) => { return inst.clone({ ...def, checks: [ ...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) ] }, { parent: true }); }; inst.with = inst.check; inst.clone = (_def, params) => clone(inst, _def, params); inst.brand = () => inst; inst.register = ((reg, meta3) => { reg.add(inst, meta3); return inst; }); inst.apply = (fn) => fn(inst); }); var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => { $ZodObject.init(inst, def); ZodMiniType.init(inst, def); defineLazy(inst, "shape", () => def.shape); }); // @__NO_SIDE_EFFECTS__ function object(shape, params) { const def = { type: "object", shape: shape ?? {}, ...normalizeParams(params) }; return new ZodMiniObject(def); } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js function isZ4Schema(s) { const schema = s; return !!schema._zod; } function objectFromShape(shape) { const values = Object.values(shape); if (values.length === 0) return object({}); const allV4 = values.every(isZ4Schema); const allV3 = values.every((s) => !isZ4Schema(s)); if (allV4) return object(shape); if (allV3) return objectType(shape); throw new Error("Mixed Zod versions detected in object shape."); } function safeParse2(schema, data) { if (isZ4Schema(schema)) { const result2 = safeParse(schema, data); return result2; } const v3Schema = schema; const result = v3Schema.safeParse(data); return result; } async function safeParseAsync2(schema, data) { if (isZ4Schema(schema)) { const result2 = await safeParseAsync(schema, data); return result2; } const v3Schema = schema; const result = await v3Schema.safeParseAsync(data); return result; } function getObjectShape(schema) { if (!schema) return void 0; let rawShape; if (isZ4Schema(schema)) { const v4Schema = schema; rawShape = v4Schema._zod?.def?.shape; } else { const v3Schema = schema; rawShape = v3Schema.shape; } if (!rawShape) return void 0; if (typeof rawShape === "function") { try { return rawShape(); } catch { return void 0; } } return rawShape; } function normalizeObjectSchema(schema) { if (!schema) return void 0; if (typeof schema === "object") { const asV3 = schema; const asV4 = schema; if (!asV3._def && !asV4._zod) { const values = Object.values(schema); if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) { return objectFromShape(schema); } } } if (isZ4Schema(schema)) { const v4Schema = schema; const def = v4Schema._zod?.def; if (def && (def.type === "object" || def.shape !== void 0)) { return schema; } } else { const v3Schema = schema; if (v3Schema.shape !== void 0) { return schema; } } return void 0; } function getParseErrorMessage(error51) { if (error51 && typeof error51 === "object") { if ("message" in error51 && typeof error51.message === "string") { return error51.message; } if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) { const firstIssue = error51.issues[0]; if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) { return String(firstIssue.message); } } try { return JSON.stringify(error51); } catch { return String(error51); } } return String(error51); } function getSchemaDescription(schema) { return schema.description; } function isSchemaOptional(schema) { if (isZ4Schema(schema)) { const v4Schema = schema; return v4Schema._zod?.def?.type === "optional"; } const v3Schema = schema; if (typeof schema.isOptional === "function") { return schema.isOptional(); } return v3Schema._def?.typeName === "ZodOptional"; } function getLiteralValue(schema) { if (isZ4Schema(schema)) { const v4Schema = schema; const def2 = v4Schema._zod?.def; if (def2) { if (def2.value !== void 0) return def2.value; if (Array.isArray(def2.values) && def2.values.length > 0) { return def2.values[0]; } } } const v3Schema = schema; const def = v3Schema._def; if (def) { if (def.value !== void 0) return def.value; if (Array.isArray(def.values) && def.values.length > 0) { return def.values[0]; } } const directValue = schema.value; if (directValue !== void 0) return directValue; return void 0; } // node_modules/@modelcontextprotocol/sdk/dist/esm/types.js init_define_KSQL_DOCS(); // node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny2, ZodArray: () => ZodArray2, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt2, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean2, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch2, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate2, ZodDefault: () => ZodDefault2, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum2, ZodError: () => ZodError2, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, ZodFunction: () => ZodFunction2, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, ZodIntersection: () => ZodIntersection2, ZodIssueCode: () => ZodIssueCode2, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy2, ZodLiteral: () => ZodLiteral2, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap2, ZodNaN: () => ZodNaN2, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever2, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull2, ZodNullable: () => ZodNullable2, ZodNumber: () => ZodNumber2, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject2, ZodOptional: () => ZodOptional2, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPreprocess: () => ZodPreprocess, ZodPromise: () => ZodPromise2, ZodReadonly: () => ZodReadonly2, ZodRealError: () => ZodRealError, ZodRecord: () => ZodRecord2, ZodSet: () => ZodSet2, ZodString: () => ZodString2, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol2, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple2, ZodType: () => ZodType2, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined2, ZodUnion: () => ZodUnion2, ZodUnknown: () => ZodUnknown2, ZodVoid: () => ZodVoid2, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, codec: () => codec, coerce: () => coerce_exports2, config: () => config, core: () => core_exports2, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, decode: () => decode2, decodeAsync: () => decodeAsync2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, encode: () => encode2, encodeAsync: () => encodeAsync2, endsWith: () => _endsWith, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, flattenError: () => flattenError, float32: () => float32, float64: () => float64, formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, getErrorMap: () => getErrorMap2, globalRegistry: () => globalRegistry, gt: () => _gt, gte: () => _gte, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, includes: () => _includes, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, invertCodec: () => invertCodec, ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports2, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, length: () => _length, literal: () => literal, locales: () => locales_exports, looseObject: () => looseObject, looseRecord: () => looseRecord, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, mac: () => mac2, map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, negative: () => _negative, never: () => never, nonnegative: () => _nonnegative, nonoptional: () => nonoptional, nonpositive: () => _nonpositive, normalize: () => _normalize, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object2, optional: () => optional, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, positive: () => _positive, prefault: () => prefault, preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, property: () => _property, readonly: () => readonly, record: () => record, refine: () => refine, regex: () => _regex, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode2, safeDecodeAsync: () => safeDecodeAsync2, safeEncode: () => safeEncode2, safeEncodeAsync: () => safeEncodeAsync2, safeParse: () => safeParse3, safeParseAsync: () => safeParseAsync3, set: () => set, setErrorMap: () => setErrorMap, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, uppercase: () => _uppercase, url: () => url, util: () => util_exports, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor }); init_define_KSQL_DOCS(); // node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny2, ZodArray: () => ZodArray2, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt2, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean2, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch2, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate2, ZodDefault: () => ZodDefault2, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum2, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFunction: () => ZodFunction2, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodIntersection: () => ZodIntersection2, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy2, ZodLiteral: () => ZodLiteral2, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap2, ZodNaN: () => ZodNaN2, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever2, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull2, ZodNullable: () => ZodNullable2, ZodNumber: () => ZodNumber2, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject2, ZodOptional: () => ZodOptional2, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPreprocess: () => ZodPreprocess, ZodPromise: () => ZodPromise2, ZodReadonly: () => ZodReadonly2, ZodRecord: () => ZodRecord2, ZodSet: () => ZodSet2, ZodString: () => ZodString2, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol2, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple2, ZodType: () => ZodType2, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined2, ZodUnion: () => ZodUnion2, ZodUnknown: () => ZodUnknown2, ZodVoid: () => ZodVoid2, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, float32: () => float32, float64: () => float64, function: () => _function, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, invertCodec: () => invertCodec, ipv4: () => ipv42, ipv6: () => ipv62, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, literal: () => literal, looseObject: () => looseObject, looseRecord: () => looseRecord, mac: () => mac2, map: () => map, meta: () => meta2, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, never: () => never, nonoptional: () => nonoptional, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object2, optional: () => optional, partialRecord: () => partialRecord, pipe: () => pipe, prefault: () => prefault, preprocess: () => preprocess, promise: () => promise, readonly: () => readonly, record: () => record, refine: () => refine, set: () => set, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, transform: () => transform, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, url: () => url, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor }); init_define_KSQL_DOCS(); // node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, gt: () => _gt, gte: () => _gte, includes: () => _includes, length: () => _length, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, maxLength: () => _maxLength, maxSize: () => _maxSize, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, negative: () => _negative, nonnegative: () => _nonnegative, nonpositive: () => _nonpositive, normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, property: () => _property, regex: () => _regex, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, trim: () => _trim, uppercase: () => _uppercase }); init_define_KSQL_DOCS(); // node_modules/zod/v4/classic/iso.js var iso_exports2 = {}; __export(iso_exports2, { ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, date: () => date2, datetime: () => datetime2, duration: () => duration2, time: () => time2 }); init_define_KSQL_DOCS(); var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); function datetime2(params) { return _isoDateTime(ZodISODateTime, params); } var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); function date2(params) { return _isoDate(ZodISODate, params); } var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); function time2(params) { return _isoTime(ZodISOTime, params); } var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); function duration2(params) { return _isoDuration(ZodISODuration, params); } // node_modules/zod/v4/classic/parse.js init_define_KSQL_DOCS(); // node_modules/zod/v4/classic/errors.js init_define_KSQL_DOCS(); var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper) // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper) // enumerable: false, }, addIssue: { value: (issue2) => { inst.issues.push(issue2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, addIssues: { value: (issues2) => { inst.issues.push(...issues2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } // enumerable: false, } }); }; var ZodError2 = /* @__PURE__ */ $constructor("ZodError", initializer2); var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { Parent: Error }); // node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError); var encode2 = /* @__PURE__ */ _encode(ZodRealError); var decode2 = /* @__PURE__ */ _decode(ZodRealError); var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); // node_modules/zod/v4/classic/schemas.js var _installedGroups = /* @__PURE__ */ new WeakMap(); function _installLazyMethods(inst, group, methods) { const proto = Object.getPrototypeOf(inst); let installed = _installedGroups.get(proto); if (!installed) { installed = /* @__PURE__ */ new Set(); _installedGroups.set(proto, installed); } if (installed.has(group)) return; installed.add(group); for (const key in methods) { const fn = methods[key]; Object.defineProperty(proto, key, { configurable: true, enumerable: false, get() { const bound = fn.bind(this); Object.defineProperty(this, key, { configurable: true, writable: true, enumerable: true, value: bound }); return bound; }, set(v) { Object.defineProperty(this, key, { configurable: true, writable: true, enumerable: true, value: v }); } }); } } var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); Object.assign(inst["~standard"], { jsonSchema: { input: createStandardJSONSchemaMethod(inst, "input"), output: createStandardJSONSchemaMethod(inst, "output") } }); inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; Object.defineProperty(inst, "_def", { value: def }); inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse3(inst, data, params); inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync3(inst, data, params); inst.spa = inst.safeParseAsync; inst.encode = (data, params) => encode2(inst, data, params); inst.decode = (data, params) => decode2(inst, data, params); inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); inst.safeEncode = (data, params) => safeEncode2(inst, data, params); inst.safeDecode = (data, params) => safeDecode2(inst, data, params); inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); _installLazyMethods(inst, "ZodType", { check(...chks) { const def2 = this.def; return this.clone(util_exports.mergeDefs(def2, { checks: [ ...def2.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) ] }), { parent: true }); }, with(...chks) { return this.check(...chks); }, clone(def2, params) { return clone(this, def2, params); }, brand() { return this; }, register(reg, meta3) { reg.add(this, meta3); return this; }, refine(check2, params) { return this.check(refine(check2, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); }, overwrite(fn) { return this.check(_overwrite(fn)); }, optional() { return optional(this); }, exactOptional() { return exactOptional(this); }, nullable() { return nullable(this); }, nullish() { return optional(nullable(this)); }, nonoptional(params) { return nonoptional(this, params); }, array() { return array(this); }, or(arg) { return union([this, arg]); }, and(arg) { return intersection(this, arg); }, transform(tx) { return pipe(this, transform(tx)); }, default(d) { return _default2(this, d); }, prefault(d) { return prefault(this, d); }, catch(params) { return _catch2(this, params); }, pipe(target) { return pipe(this, target); }, readonly() { return readonly(this); }, describe(description) { const cl = this.clone(); globalRegistry.add(cl, { description }); return cl; }, meta(...args) { if (args.length === 0) return globalRegistry.get(this); const cl = this.clone(); globalRegistry.add(cl, args[0]); return cl; }, isOptional() { return this.safeParse(void 0).success; }, isNullable() { return this.safeParse(null).success; }, apply(fn) { return fn(this); } }); Object.defineProperty(inst, "description", { get() { return globalRegistry.get(inst)?.description; }, configurable: true }); return inst; }); var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { $ZodString.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); const bag = inst._zod.bag; inst.format = bag.format ?? null; inst.minLength = bag.minimum ?? null; inst.maxLength = bag.maximum ?? null; _installLazyMethods(inst, "_ZodString", { regex(...args) { return this.check(_regex(...args)); }, includes(...args) { return this.check(_includes(...args)); }, startsWith(...args) { return this.check(_startsWith(...args)); }, endsWith(...args) { return this.check(_endsWith(...args)); }, min(...args) { return this.check(_minLength(...args)); }, max(...args) { return this.check(_maxLength(...args)); }, length(...args) { return this.check(_length(...args)); }, nonempty(...args) { return this.check(_minLength(1, ...args)); }, lowercase(params) { return this.check(_lowercase(params)); }, uppercase(params) { return this.check(_uppercase(params)); }, trim() { return this.check(_trim()); }, normalize(...args) { return this.check(_normalize(...args)); }, toLowerCase() { return this.check(_toLowerCase()); }, toUpperCase() { return this.check(_toUpperCase()); }, slugify() { return this.check(_slugify()); } }); }); var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); inst.email = (params) => inst.check(_email(ZodEmail, params)); inst.url = (params) => inst.check(_url(ZodURL, params)); inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); inst.xid = (params) => inst.check(_xid(ZodXID, params)); inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); inst.e164 = (params) => inst.check(_e164(ZodE164, params)); inst.datetime = (params) => inst.check(datetime2(params)); inst.date = (params) => inst.check(date2(params)); inst.time = (params) => inst.check(time2(params)); inst.duration = (params) => inst.check(duration2(params)); }); function string2(params) { return _string(ZodString2, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); function email2(params) { return _email(ZodEmail, params); } var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); function guid2(params) { return _guid(ZodGUID, params); } var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); function uuid2(params) { return _uuid(ZodUUID, params); } function uuidv4(params) { return _uuidv4(ZodUUID, params); } function uuidv6(params) { return _uuidv6(ZodUUID, params); } function uuidv7(params) { return _uuidv7(ZodUUID, params); } var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); function url(params) { return _url(ZodURL, params); } function httpUrl(params) { return _url(ZodURL, { protocol: regexes_exports.httpProtocol, hostname: regexes_exports.domain, ...util_exports.normalizeParams(params) }); } var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); function emoji2(params) { return _emoji2(ZodEmoji, params); } var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); function nanoid2(params) { return _nanoid(ZodNanoID, params); } var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid3(params) { return _cuid(ZodCUID, params); } var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid22(params) { return _cuid2(ZodCUID2, params); } var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); function ulid2(params) { return _ulid(ZodULID, params); } var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); function xid2(params) { return _xid(ZodXID, params); } var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); function ksuid2(params) { return _ksuid(ZodKSUID, params); } var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv42(params) { return _ipv4(ZodIPv4, params); } var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { $ZodMAC.init(inst, def); ZodStringFormat.init(inst, def); }); function mac2(params) { return _mac(ZodMAC, params); } var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv62(params) { return _ipv6(ZodIPv6, params); } var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv42(params) { return _cidrv4(ZodCIDRv4, params); } var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv62(params) { return _cidrv6(ZodCIDRv6, params); } var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); function base642(params) { return _base64(ZodBase64, params); } var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); function base64url2(params) { return _base64url(ZodBase64URL, params); } var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); function e1642(params) { return _e164(ZodE164, params); } var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); function jwt(params) { return _jwt(ZodJWT, params); } var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { $ZodCustomStringFormat.init(inst, def); ZodStringFormat.init(inst, def); }); function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); } function hex2(_params) { return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; const format = `${alg}_${enc}`; const regex = regexes_exports[format]; if (!regex) throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { $ZodNumber.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); _installLazyMethods(inst, "ZodNumber", { gt(value, params) { return this.check(_gt(value, params)); }, gte(value, params) { return this.check(_gte(value, params)); }, min(value, params) { return this.check(_gte(value, params)); }, lt(value, params) { return this.check(_lt(value, params)); }, lte(value, params) { return this.check(_lte(value, params)); }, max(value, params) { return this.check(_lte(value, params)); }, int(params) { return this.check(int(params)); }, safe(params) { return this.check(int(params)); }, positive(params) { return this.check(_gt(0, params)); }, nonnegative(params) { return this.check(_gte(0, params)); }, negative(params) { return this.check(_lt(0, params)); }, nonpositive(params) { return this.check(_lte(0, params)); }, multipleOf(value, params) { return this.check(_multipleOf(value, params)); }, step(value, params) { return this.check(_multipleOf(value, params)); }, finite() { return this; } }); const bag = inst._zod.bag; inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); inst.isFinite = true; inst.format = bag.format ?? null; }); function number2(params) { return _number(ZodNumber2, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodNumber2.init(inst, def); }); function int(params) { return _int(ZodNumberFormat, params); } function float32(params) { return _float32(ZodNumberFormat, params); } function float64(params) { return _float64(ZodNumberFormat, params); } function int32(params) { return _int32(ZodNumberFormat, params); } function uint32(params) { return _uint32(ZodNumberFormat, params); } var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); }); function boolean2(params) { return _boolean(ZodBoolean2, params); } var ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { $ZodBigInt.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.positive = (params) => inst.check(_gt(BigInt(0), params)); inst.negative = (params) => inst.check(_lt(BigInt(0), params)); inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); const bag = inst._zod.bag; inst.minValue = bag.minimum ?? null; inst.maxValue = bag.maximum ?? null; inst.format = bag.format ?? null; }); function bigint2(params) { return _bigint(ZodBigInt2, params); } var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { $ZodBigIntFormat.init(inst, def); ZodBigInt2.init(inst, def); }); function int64(params) { return _int64(ZodBigIntFormat, params); } function uint64(params) { return _uint64(ZodBigIntFormat, params); } var ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { $ZodSymbol.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); }); function symbol(params) { return _symbol(ZodSymbol2, params); } var ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { $ZodUndefined.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); }); function _undefined3(params) { return _undefined2(ZodUndefined2, params); } var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); }); function _null3(params) { return _null2(ZodNull2, params); } var ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { $ZodAny.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); }); function any() { return _any(ZodAny2); } var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); }); function unknown() { return _unknown(ZodUnknown2); } var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); }); function never(params) { return _never(ZodNever2, params); } var ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { $ZodVoid.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); }); function _void2(params) { return _void(ZodVoid2, params); } var ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { $ZodDate.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); inst.min = (value, params) => inst.check(_gte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); const c = inst._zod.bag; inst.minDate = c.minimum ? new Date(c.minimum) : null; inst.maxDate = c.maximum ? new Date(c.maximum) : null; }); function date3(params) { return _date(ZodDate2, params); } var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); inst.element = def.element; _installLazyMethods(inst, "ZodArray", { min(n, params) { return this.check(_minLength(n, params)); }, nonempty(params) { return this.check(_minLength(1, params)); }, max(n, params) { return this.check(_maxLength(n, params)); }, length(n, params) { return this.check(_length(n, params)); }, unwrap() { return this.element; } }); }); function array(element, params) { return _array(ZodArray2, element, params); } function keyof(schema) { const shape = schema._zod.def.shape; return _enum2(Object.keys(shape)); } var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { $ZodObjectJIT.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); util_exports.defineLazy(inst, "shape", () => { return def.shape; }); _installLazyMethods(inst, "ZodObject", { keyof() { return _enum2(Object.keys(this._zod.def.shape)); }, catchall(catchall) { return this.clone({ ...this._zod.def, catchall }); }, passthrough() { return this.clone({ ...this._zod.def, catchall: unknown() }); }, loose() { return this.clone({ ...this._zod.def, catchall: unknown() }); }, strict() { return this.clone({ ...this._zod.def, catchall: never() }); }, strip() { return this.clone({ ...this._zod.def, catchall: void 0 }); }, extend(incoming) { return util_exports.extend(this, incoming); }, safeExtend(incoming) { return util_exports.safeExtend(this, incoming); }, merge(other) { return util_exports.merge(this, other); }, pick(mask) { return util_exports.pick(this, mask); }, omit(mask) { return util_exports.omit(this, mask); }, partial(...args) { return util_exports.partial(ZodOptional2, this, args[0]); }, required(...args) { return util_exports.required(ZodNonOptional, this, args[0]); } }); }); function object2(shape, params) { const def = { type: "object", shape: shape ?? {}, ...util_exports.normalizeParams(params) }; return new ZodObject2(def); } function strictObject(shape, params) { return new ZodObject2({ type: "object", shape, catchall: never(), ...util_exports.normalizeParams(params) }); } function looseObject(shape, params) { return new ZodObject2({ type: "object", shape, catchall: unknown(), ...util_exports.normalizeParams(params) }); } var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); function union(options, params) { return new ZodUnion2({ type: "union", options, ...util_exports.normalizeParams(params) }); } var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { ZodUnion2.init(inst, def); $ZodXor.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); function xor(options, params) { return new ZodXor({ type: "union", options, inclusive: false, ...util_exports.normalizeParams(params) }); } var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { ZodUnion2.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); function discriminatedUnion(discriminator, options, params) { return new ZodDiscriminatedUnion2({ type: "union", options, discriminator, ...util_exports.normalizeParams(params) }); } var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); }); function intersection(left, right) { return new ZodIntersection2({ type: "intersection", left, right }); } var ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { $ZodTuple.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); inst.rest = (rest) => inst.clone({ ...inst._zod.def, rest }); }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodTuple2({ type: "tuple", items, rest, ...util_exports.normalizeParams(params) }); } var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record(keyType, valueType, params) { if (!valueType || !valueType._zod) { return new ZodRecord2({ type: "record", keyType: string2(), valueType: keyType, ...util_exports.normalizeParams(valueType) }); } return new ZodRecord2({ type: "record", keyType, valueType, ...util_exports.normalizeParams(params) }); } function partialRecord(keyType, valueType, params) { const k = clone(keyType); k._zod.values = void 0; return new ZodRecord2({ type: "record", keyType: k, valueType, ...util_exports.normalizeParams(params) }); } function looseRecord(keyType, valueType, params) { return new ZodRecord2({ type: "record", keyType, valueType, mode: "loose", ...util_exports.normalizeParams(params) }); } var ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { $ZodMap.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; inst.min = (...args) => inst.check(_minSize(...args)); inst.nonempty = (params) => inst.check(_minSize(1, params)); inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); function map(keyType, valueType, params) { return new ZodMap2({ type: "map", keyType, valueType, ...util_exports.normalizeParams(params) }); } var ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { $ZodSet.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); inst.min = (...args) => inst.check(_minSize(...args)); inst.nonempty = (params) => inst.check(_minSize(1, params)); inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); function set(valueType, params) { return new ZodSet2({ type: "set", valueType, ...util_exports.normalizeParams(params) }); } var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); inst.enum = def.entries; inst.options = Object.values(def.entries); const keys = new Set(Object.keys(def.entries)); inst.extract = (values, params) => { const newEntries = {}; for (const value of values) { if (keys.has(value)) { newEntries[value] = def.entries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum2({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; inst.exclude = (values, params) => { const newEntries = { ...def.entries }; for (const value of values) { if (keys.has(value)) { delete newEntries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum2({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; }); function _enum2(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodEnum2({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } function nativeEnum(entries, params) { return new ZodEnum2({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { get() { if (def.values.length > 1) { throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } return def.values[0]; } }); }); function literal(value, params) { return new ZodLiteral2({ type: "literal", values: Array.isArray(value) ? value : [value], ...util_exports.normalizeParams(params) }); } var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { $ZodFile.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); inst.min = (size, params) => inst.check(_minSize(size, params)); inst.max = (size, params) => inst.check(_maxSize(size, params)); inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); }); function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); inst._zod.parse = (payload, _ctx) => { if (_ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } payload.addIssue = (issue2) => { if (typeof issue2 === "string") { payload.issues.push(util_exports.issue(issue2, payload.value, def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output2) => { payload.value = output2; payload.fallback = true; return payload; }); } payload.value = output; payload.fallback = true; return payload; }; }); function transform(fn) { return new ZodTransform({ type: "transform", transform: fn }); } var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { return new ZodOptional2({ type: "optional", innerType }); } var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { $ZodExactOptional.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function exactOptional(innerType) { return new ZodExactOptional({ type: "optional", innerType }); } var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { return new ZodNullable2({ type: "nullable", innerType }); } function nullish2(innerType) { return optional(nullable(innerType)); } var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function _default2(innerType, defaultValue) { return new ZodDefault2({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { return new ZodPrefault({ type: "prefault", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional({ type: "nonoptional", innerType, ...util_exports.normalizeParams(params) }); } var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { $ZodSuccess.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function success(innerType) { return new ZodSuccess({ type: "success", innerType }); } var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function _catch2(innerType, catchValue) { return new ZodCatch2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } var ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { $ZodNaN.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); }); function nan(params) { return _nan(ZodNaN2, params); } var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); inst.in = def.in; inst.out = def.out; }); function pipe(in_, out) { return new ZodPipe({ type: "pipe", in: in_, out // ...util.normalizeParams(params), }); } var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { ZodPipe.init(inst, def); $ZodCodec.init(inst, def); }); function codec(in_, out, params) { return new ZodCodec({ type: "pipe", in: in_, out, transform: params.decode, reverseTransform: params.encode }); } function invertCodec(codec2) { const def = codec2._zod.def; return new ZodCodec({ type: "pipe", in: def.out, out: def.in, transform: def.reverseTransform, reverseTransform: def.transform }); } var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => { ZodPipe.init(inst, def); $ZodPreprocess.init(inst, def); }); var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function readonly(innerType) { return new ZodReadonly2({ type: "readonly", innerType }); } var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); }); function templateLiteral(parts, params) { return new ZodTemplateLiteral({ type: "template_literal", parts, ...util_exports.normalizeParams(params) }); } var ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { $ZodLazy.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.getter(); }); function lazy(getter) { return new ZodLazy2({ type: "lazy", getter }); } var ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { $ZodPromise.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function promise(innerType) { return new ZodPromise2({ type: "promise", innerType }); } var ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { $ZodFunction.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); }); function _function(params) { return new ZodFunction2({ type: "function", input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), output: params?.output ?? unknown() }); } var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); }); function check(fn) { const ch = new $ZodCheck({ check: "custom" // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; } function custom(fn, _params) { return _custom(ZodCustom, fn ?? (() => true), _params); } function refine(fn, _params = {}) { return _refine(ZodCustom, fn, _params); } function superRefine(fn, params) { return _superRefine(fn, params); } var describe2 = describe; var meta2 = meta; function _instanceof(cls, params = {}) { const inst = new ZodCustom({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true, ...util_exports.normalizeParams(params) }); inst._zod.bag.Class = cls; inst._zod.check = (payload) => { if (!(payload.value instanceof cls)) { payload.issues.push({ code: "invalid_type", expected: cls.name, input: payload.value, inst, path: [...inst._zod.def.path ?? []] }); } }; return inst; } var stringbool = (...args) => _stringbool({ Codec: ZodCodec, Boolean: ZodBoolean2, String: ZodString2 }, ...args); function json(params) { const jsonSchema = lazy(() => { return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); }); return jsonSchema; } function preprocess(fn, schema) { return new ZodPreprocess({ type: "pipe", in: transform(fn), out: schema }); } // node_modules/zod/v4/classic/compat.js init_define_KSQL_DOCS(); var ZodIssueCode2 = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" }; function setErrorMap(map2) { config({ customError: map2 }); } function getErrorMap2() { return config().customError; } var ZodFirstPartyTypeKind2; /* @__PURE__ */ (function(ZodFirstPartyTypeKind3) { })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); // node_modules/zod/v4/classic/from-json-schema.js init_define_KSQL_DOCS(); var z = { ...schemas_exports2, ...checks_exports2, iso: iso_exports2 }; var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ // Schema identification "$schema", "$ref", "$defs", "definitions", // Core schema keywords "$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor", // Type "type", "enum", "const", // Composition "anyOf", "oneOf", "allOf", "not", // Object "properties", "required", "additionalProperties", "patternProperties", "propertyNames", "minProperties", "maxProperties", // Array "items", "prefixItems", "additionalItems", "minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains", // String "minLength", "maxLength", "pattern", "format", // Number "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", // Already handled metadata "description", "default", // Content "contentEncoding", "contentMediaType", "contentSchema", // Unsupported (error-throwing) "unevaluatedItems", "unevaluatedProperties", "if", "then", "else", "dependentSchemas", "dependentRequired", // OpenAPI "nullable", "readOnly" ]); function detectVersion(schema, defaultTarget) { const $schema = schema.$schema; if ($schema === "https://json-schema.org/draft/2020-12/schema") { return "draft-2020-12"; } if ($schema === "http://json-schema.org/draft-07/schema#") { return "draft-7"; } if ($schema === "http://json-schema.org/draft-04/schema#") { return "draft-4"; } return defaultTarget ?? "draft-2020-12"; } function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); } const path = ref.slice(1).split("/").filter(Boolean); if (path.length === 0) { return ctx.rootSchema; } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { const key = path[1]; if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } return ctx.defs[key]; } throw new Error(`Reference not found: ${ref}`); } function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { return z.never(); } throw new Error("not is not supported in Zod (except { not: {} } for never)"); } if (schema.unevaluatedItems !== void 0) { throw new Error("unevaluatedItems is not supported"); } if (schema.unevaluatedProperties !== void 0) { throw new Error("unevaluatedProperties is not supported"); } if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) { throw new Error("Conditional schemas (if/then/else) are not supported"); } if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) { throw new Error("dependentSchemas and dependentRequired are not supported"); } if (schema.$ref) { const refPath = schema.$ref; if (ctx.refs.has(refPath)) { return ctx.refs.get(refPath); } if (ctx.processing.has(refPath)) { return z.lazy(() => { if (!ctx.refs.has(refPath)) { throw new Error(`Circular reference not resolved: ${refPath}`); } return ctx.refs.get(refPath); }); } ctx.processing.add(refPath); const resolved = resolveRef(refPath, ctx); const zodSchema2 = convertSchema(resolved, ctx); ctx.refs.set(refPath, zodSchema2); ctx.processing.delete(refPath); return zodSchema2; } if (schema.enum !== void 0) { const enumValues = schema.enum; if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) { return z.null(); } if (enumValues.length === 0) { return z.never(); } if (enumValues.length === 1) { return z.literal(enumValues[0]); } if (enumValues.every((v) => typeof v === "string")) { return z.enum(enumValues); } const literalSchemas = enumValues.map((v) => z.literal(v)); if (literalSchemas.length < 2) { return literalSchemas[0]; } return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); } if (schema.const !== void 0) { return z.literal(schema.const); } const type = schema.type; if (Array.isArray(type)) { const typeSchemas = type.map((t) => { const typeSchema = { ...schema, type: t }; return convertBaseSchema(typeSchema, ctx); }); if (typeSchemas.length === 0) { return z.never(); } if (typeSchemas.length === 1) { return typeSchemas[0]; } return z.union(typeSchemas); } if (!type) { return z.any(); } let zodSchema; switch (type) { case "string": { let stringSchema = z.string(); if (schema.format) { const format = schema.format; if (format === "email") { stringSchema = stringSchema.check(z.email()); } else if (format === "uri" || format === "uri-reference") { stringSchema = stringSchema.check(z.url()); } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { stringSchema = stringSchema.check(z.iso.datetime()); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { stringSchema = stringSchema.check(z.iso.time()); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { stringSchema = stringSchema.check(z.ipv6()); } else if (format === "mac") { stringSchema = stringSchema.check(z.mac()); } else if (format === "cidr") { stringSchema = stringSchema.check(z.cidrv4()); } else if (format === "cidr-v6") { stringSchema = stringSchema.check(z.cidrv6()); } else if (format === "base64") { stringSchema = stringSchema.check(z.base64()); } else if (format === "base64url") { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { stringSchema = stringSchema.check(z.emoji()); } else if (format === "nanoid") { stringSchema = stringSchema.check(z.nanoid()); } else if (format === "cuid") { stringSchema = stringSchema.check(z.cuid()); } else if (format === "cuid2") { stringSchema = stringSchema.check(z.cuid2()); } else if (format === "ulid") { stringSchema = stringSchema.check(z.ulid()); } else if (format === "xid") { stringSchema = stringSchema.check(z.xid()); } else if (format === "ksuid") { stringSchema = stringSchema.check(z.ksuid()); } } if (typeof schema.minLength === "number") { stringSchema = stringSchema.min(schema.minLength); } if (typeof schema.maxLength === "number") { stringSchema = stringSchema.max(schema.maxLength); } if (schema.pattern) { stringSchema = stringSchema.regex(new RegExp(schema.pattern)); } zodSchema = stringSchema; break; } case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); if (typeof schema.minimum === "number") { numberSchema = numberSchema.min(schema.minimum); } if (typeof schema.maximum === "number") { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { numberSchema = numberSchema.gt(schema.exclusiveMinimum); } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { numberSchema = numberSchema.gt(schema.minimum); } if (typeof schema.exclusiveMaximum === "number") { numberSchema = numberSchema.lt(schema.exclusiveMaximum); } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { numberSchema = numberSchema.lt(schema.maximum); } if (typeof schema.multipleOf === "number") { numberSchema = numberSchema.multipleOf(schema.multipleOf); } zodSchema = numberSchema; break; } case "boolean": { zodSchema = z.boolean(); break; } case "null": { zodSchema = z.null(); break; } case "object": { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); } if (schema.propertyNames) { const keySchema = convertSchema(schema.propertyNames, ctx); const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); if (Object.keys(shape).length === 0) { zodSchema = z.record(keySchema, valueSchema); break; } const objectSchema2 = z.object(shape).passthrough(); const recordSchema = z.looseRecord(keySchema, valueSchema); zodSchema = z.intersection(objectSchema2, recordSchema); break; } if (schema.patternProperties) { const patternProps = schema.patternProperties; const patternKeys = Object.keys(patternProps); const looseRecords = []; for (const pattern of patternKeys) { const patternValue = convertSchema(patternProps[pattern], ctx); const keySchema = z.string().regex(new RegExp(pattern)); looseRecords.push(z.looseRecord(keySchema, patternValue)); } const schemasToIntersect = []; if (Object.keys(shape).length > 0) { schemasToIntersect.push(z.object(shape).passthrough()); } schemasToIntersect.push(...looseRecords); if (schemasToIntersect.length === 0) { zodSchema = z.object({}).passthrough(); } else if (schemasToIntersect.length === 1) { zodSchema = schemasToIntersect[0]; } else { let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); for (let i = 2; i < schemasToIntersect.length; i++) { result = z.intersection(result, schemasToIntersect[i]); } zodSchema = result; } break; } const objectSchema = z.object(shape); if (schema.additionalProperties === false) { zodSchema = objectSchema.strict(); } else if (typeof schema.additionalProperties === "object") { zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); } else { zodSchema = objectSchema.passthrough(); } break; } case "array": { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; if (rest) { zodSchema = z.tuple(tupleItems).rest(rest); } else { zodSchema = z.tuple(tupleItems); } if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } if (typeof schema.maxItems === "number") { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { const tupleItems = items.map((item) => convertSchema(item, ctx)); const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; if (rest) { zodSchema = z.tuple(tupleItems).rest(rest); } else { zodSchema = z.tuple(tupleItems); } if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } if (typeof schema.maxItems === "number") { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (items !== void 0) { const element = convertSchema(items, ctx); let arraySchema = z.array(element); if (typeof schema.minItems === "number") { arraySchema = arraySchema.min(schema.minItems); } if (typeof schema.maxItems === "number") { arraySchema = arraySchema.max(schema.maxItems); } zodSchema = arraySchema; } else { zodSchema = z.array(z.any()); } break; } default: throw new Error(`Unsupported type: ${type}`); } return zodSchema; } function convertSchema(schema, ctx) { if (typeof schema === "boolean") { return schema ? z.any() : z.never(); } let baseSchema = convertBaseSchema(schema, ctx); const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0; if (schema.anyOf && Array.isArray(schema.anyOf)) { const options = schema.anyOf.map((s) => convertSchema(s, ctx)); const anyOfUnion = z.union(options); baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; } if (schema.oneOf && Array.isArray(schema.oneOf)) { const options = schema.oneOf.map((s) => convertSchema(s, ctx)); const oneOfUnion = z.xor(options); baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; } if (schema.allOf && Array.isArray(schema.allOf)) { if (schema.allOf.length === 0) { baseSchema = hasExplicitType ? baseSchema : z.any(); } else { let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); const startIdx = hasExplicitType ? 0 : 1; for (let i = startIdx; i < schema.allOf.length; i++) { result = z.intersection(result, convertSchema(schema.allOf[i], ctx)); } baseSchema = result; } } if (schema.nullable === true && ctx.version === "openapi-3.0") { baseSchema = z.nullable(baseSchema); } if (schema.readOnly === true) { baseSchema = z.readonly(baseSchema); } if (schema.default !== void 0) { baseSchema = baseSchema.default(schema.default); } const extraMeta = {}; const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; for (const key of coreMetadataKeys) { if (key in schema) { extraMeta[key] = schema[key]; } } const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; for (const key of contentMetadataKeys) { if (key in schema) { extraMeta[key] = schema[key]; } } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { extraMeta[key] = schema[key]; } } if (Object.keys(extraMeta).length > 0) { ctx.registry.add(baseSchema, extraMeta); } if (schema.description) { baseSchema = baseSchema.describe(schema.description); } return baseSchema; } function fromJSONSchema(schema, params) { if (typeof schema === "boolean") { return schema ? z.any() : z.never(); } let normalized; try { normalized = JSON.parse(JSON.stringify(schema)); } catch { throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas"); } const version2 = detectVersion(normalized, params?.defaultTarget); const defs = normalized.$defs || normalized.definitions || {}; const ctx = { version: version2, defs, refs: /* @__PURE__ */ new Map(), processing: /* @__PURE__ */ new Set(), rootSchema: normalized, registry: params?.registry ?? globalRegistry }; return convertSchema(normalized, ctx); } // node_modules/zod/v4/classic/coerce.js var coerce_exports2 = {}; __export(coerce_exports2, { bigint: () => bigint3, boolean: () => boolean3, date: () => date4, number: () => number3, string: () => string3 }); init_define_KSQL_DOCS(); function string3(params) { return _coercedString(ZodString2, params); } function number3(params) { return _coercedNumber(ZodNumber2, params); } function boolean3(params) { return _coercedBoolean(ZodBoolean2, params); } function bigint3(params) { return _coercedBigint(ZodBigInt2, params); } function date4(params) { return _coercedDate(ZodDate2, params); } // node_modules/zod/v4/classic/external.js config(en_default2()); // node_modules/@modelcontextprotocol/sdk/dist/esm/types.js var LATEST_PROTOCOL_VERSION = "2025-11-25"; var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; var JSONRPC_VERSION = "2.0"; var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function")); var ProgressTokenSchema = union([string2(), number2().int()]); var CursorSchema = string2(); var TaskCreationParamsSchema = looseObject({ /** * Requested duration in milliseconds to retain task from creation. */ ttl: number2().optional(), /** * Time in milliseconds to wait between task status requests. */ pollInterval: number2().optional() }); var TaskMetadataSchema = object2({ ttl: number2().optional() }); var RelatedTaskMetadataSchema = object2({ taskId: string2() }); var RequestMetaSchema = looseObject({ /** * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. */ progressToken: ProgressTokenSchema.optional(), /** * If specified, this request is related to the provided task. */ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() }); var BaseRequestParamsSchema = object2({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ _meta: RequestMetaSchema.optional() }); var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * If specified, the caller is requesting task-augmented execution for this request. * The request will return a CreateTaskResult immediately, and the actual result can be * retrieved later via tasks/result. * * Task augmentation is subject to capability negotiation - receivers MUST declare support * for task augmentation of specific request types in their capabilities. */ task: TaskMetadataSchema.optional() }); var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; var RequestSchema = object2({ method: string2(), params: BaseRequestParamsSchema.loose().optional() }); var NotificationsParamsSchema = object2({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); var NotificationSchema = object2({ method: string2(), params: NotificationsParamsSchema.loose().optional() }); var ResultSchema = looseObject({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); var RequestIdSchema = union([string2(), number2().int()]); var JSONRPCRequestSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, ...RequestSchema.shape }).strict(); var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; var JSONRPCNotificationSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), ...NotificationSchema.shape }).strict(); var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; var JSONRPCResultResponseSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, result: ResultSchema }).strict(); var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; var ErrorCode; (function(ErrorCode2) { ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode || (ErrorCode = {})); var JSONRPCErrorResponseSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema.optional(), error: object2({ /** * The error type that occurred. */ code: number2().int(), /** * A short description of the error. The message SHOULD be limited to a concise single sentence. */ message: string2(), /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ data: unknown().optional() }) }).strict(); var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; var JSONRPCMessageSchema = union([ JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema ]); var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); var EmptyResultSchema = ResultSchema.strict(); var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the request to cancel. * * This MUST correspond to the ID of a request previously issued in the same direction. */ requestId: RequestIdSchema.optional(), /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ reason: string2().optional() }); var CancelledNotificationSchema = NotificationSchema.extend({ method: literal("notifications/cancelled"), params: CancelledNotificationParamsSchema }); var IconSchema = object2({ /** * URL or data URI for the icon. */ src: string2(), /** * Optional MIME type for the icon. */ mimeType: string2().optional(), /** * Optional array of strings that specify sizes at which the icon can be used. * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. * * If not provided, the client should assume that the icon can be used at any size. */ sizes: array(string2()).optional(), /** * Optional specifier for the theme this icon is designed for. `light` indicates * the icon is designed to be used with a light background, and `dark` indicates * the icon is designed to be used with a dark background. * * If not provided, the client should assume the icon can be used with any theme. */ theme: _enum2(["light", "dark"]).optional() }); var IconsSchema = object2({ /** * Optional set of sized icons that the client can display in a user interface. * * Clients that support rendering icons MUST support at least the following MIME types: * - `image/png` - PNG images (safe, universal compatibility) * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) * * Clients that support rendering icons SHOULD also support: * - `image/svg+xml` - SVG images (scalable but requires security precautions) * - `image/webp` - WebP images (modern, efficient format) */ icons: array(IconSchema).optional() }); var BaseMetadataSchema = object2({ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ name: string2(), /** * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, * even by those unfamiliar with domain-specific terminology. * * If not provided, the name should be used for display (except for Tool, * where `annotations.title` should be given precedence over using `name`, * if present). */ title: string2().optional() }); var ImplementationSchema = BaseMetadataSchema.extend({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, version: string2(), /** * An optional URL of the website for this implementation. */ websiteUrl: string2().optional(), /** * An optional human-readable description of what this implementation does. * * This can be used by clients or servers to provide context about their purpose * and capabilities. For example, a server might describe the types of resources * or tools it provides, while a client might describe its intended use case. */ description: string2().optional() }); var FormElicitationCapabilitySchema = intersection(object2({ applyDefaults: boolean2().optional() }), record(string2(), unknown())); var ElicitationCapabilitySchema = preprocess((value) => { if (value && typeof value === "object" && !Array.isArray(value)) { if (Object.keys(value).length === 0) { return { form: {} }; } } return value; }, intersection(object2({ form: FormElicitationCapabilitySchema.optional(), url: AssertObjectSchema.optional() }), record(string2(), unknown()).optional())); var ClientTasksCapabilitySchema = looseObject({ /** * Present if the client supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the client supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for sampling requests. */ sampling: looseObject({ createMessage: AssertObjectSchema.optional() }).optional(), /** * Task support for elicitation requests. */ elicitation: looseObject({ create: AssertObjectSchema.optional() }).optional() }).optional() }); var ServerTasksCapabilitySchema = looseObject({ /** * Present if the server supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the server supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for tool requests. */ tools: looseObject({ call: AssertObjectSchema.optional() }).optional() }).optional() }); var ClientCapabilitiesSchema = object2({ /** * Experimental, non-standard capabilities that the client supports. */ experimental: record(string2(), AssertObjectSchema).optional(), /** * Present if the client supports sampling from an LLM. */ sampling: object2({ /** * Present if the client supports context inclusion via includeContext parameter. * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). */ context: AssertObjectSchema.optional(), /** * Present if the client supports tool use via tools and toolChoice parameters. */ tools: AssertObjectSchema.optional() }).optional(), /** * Present if the client supports eliciting user input. */ elicitation: ElicitationCapabilitySchema.optional(), /** * Present if the client supports listing roots. */ roots: object2({ /** * Whether the client supports issuing notifications for changes to the roots list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the client supports task creation. */ tasks: ClientTasksCapabilitySchema.optional(), /** * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(string2(), AssertObjectSchema).optional() }); var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. */ protocolVersion: string2(), capabilities: ClientCapabilitiesSchema, clientInfo: ImplementationSchema }); var InitializeRequestSchema = RequestSchema.extend({ method: literal("initialize"), params: InitializeRequestParamsSchema }); var ServerCapabilitiesSchema = object2({ /** * Experimental, non-standard capabilities that the server supports. */ experimental: record(string2(), AssertObjectSchema).optional(), /** * Present if the server supports sending log messages to the client. */ logging: AssertObjectSchema.optional(), /** * Present if the server supports sending completions to the client. */ completions: AssertObjectSchema.optional(), /** * Present if the server offers any prompt templates. */ prompts: object2({ /** * Whether this server supports issuing notifications for changes to the prompt list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server offers any resources to read. */ resources: object2({ /** * Whether this server supports clients subscribing to resource updates. */ subscribe: boolean2().optional(), /** * Whether this server supports issuing notifications for changes to the resource list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server offers any tools to call. */ tools: object2({ /** * Whether this server supports issuing notifications for changes to the tool list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server supports task creation. */ tasks: ServerTasksCapabilitySchema.optional(), /** * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(string2(), AssertObjectSchema).optional() }); var InitializeResultSchema = ResultSchema.extend({ /** * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. */ protocolVersion: string2(), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, /** * Instructions describing how to use the server and its features. * * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. */ instructions: string2().optional() }); var InitializedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/initialized"), params: NotificationsParamsSchema.optional() }); var PingRequestSchema = RequestSchema.extend({ method: literal("ping"), params: BaseRequestParamsSchema.optional() }); var ProgressSchema = object2({ /** * The progress thus far. This should increase every time progress is made, even if the total is unknown. */ progress: number2(), /** * Total number of items to process (or total progress required), if known. */ total: optional(number2()), /** * An optional message describing the current progress. */ message: optional(string2()) }); var ProgressNotificationParamsSchema = object2({ ...NotificationsParamsSchema.shape, ...ProgressSchema.shape, /** * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. */ progressToken: ProgressTokenSchema }); var ProgressNotificationSchema = NotificationSchema.extend({ method: literal("notifications/progress"), params: ProgressNotificationParamsSchema }); var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * An opaque token representing the current pagination position. * If provided, the server should return results starting after this cursor. */ cursor: CursorSchema.optional() }); var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); var PaginatedResultSchema = ResultSchema.extend({ /** * An opaque token representing the pagination position after the last returned result. * If present, there may be more results available. */ nextCursor: CursorSchema.optional() }); var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]); var TaskSchema = object2({ taskId: string2(), status: TaskStatusSchema, /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. */ ttl: union([number2(), _null3()]), /** * ISO 8601 timestamp when the task was created. */ createdAt: string2(), /** * ISO 8601 timestamp when the task was last updated. */ lastUpdatedAt: string2(), pollInterval: optional(number2()), /** * Optional diagnostic message for failed tasks or other status information. */ statusMessage: optional(string2()) }); var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); var TaskStatusNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tasks/status"), params: TaskStatusNotificationParamsSchema }); var GetTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/get"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var GetTaskResultSchema = ResultSchema.merge(TaskSchema); var GetTaskPayloadRequestSchema = RequestSchema.extend({ method: literal("tasks/result"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var GetTaskPayloadResultSchema = ResultSchema.loose(); var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); var CancelTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/cancel"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); var ResourceContentsSchema = object2({ /** * The URI of this resource. */ uri: string2(), /** * The MIME type of this resource, if known. */ mimeType: optional(string2()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var TextResourceContentsSchema = ResourceContentsSchema.extend({ /** * The text of the item. This must only be set if the item can actually be represented as text (not binary data). */ text: string2() }); var Base64Schema = string2().refine((val) => { try { atob(val); return true; } catch { return false; } }, { message: "Invalid Base64 string" }); var BlobResourceContentsSchema = ResourceContentsSchema.extend({ /** * A base64-encoded string representing the binary data of the item. */ blob: Base64Schema }); var RoleSchema = _enum2(["user", "assistant"]); var AnnotationsSchema = object2({ /** * Intended audience(s) for the resource. */ audience: array(RoleSchema).optional(), /** * Importance hint for the resource, from 0 (least) to 1 (most). */ priority: number2().min(0).max(1).optional(), /** * ISO 8601 timestamp for the most recent modification. */ lastModified: iso_exports2.datetime({ offset: true }).optional() }); var ResourceSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * The URI of this resource. */ uri: string2(), /** * A description of what this resource represents. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ description: optional(string2()), /** * The MIME type of this resource, if known. */ mimeType: optional(string2()), /** * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. * * This can be used by Hosts to display file sizes and estimate context window usage. */ size: optional(number2()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ResourceTemplateSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A URI template (according to RFC 6570) that can be used to construct resource URIs. */ uriTemplate: string2(), /** * A description of what this template is for. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ description: optional(string2()), /** * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. */ mimeType: optional(string2()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. * * @format uri */ uri: string2() }); var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; var ReadResourceRequestSchema = RequestSchema.extend({ method: literal("resources/read"), params: ReadResourceRequestParamsSchema }); var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); var ResourceListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/list_changed"), params: NotificationsParamsSchema.optional() }); var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; var SubscribeRequestSchema = RequestSchema.extend({ method: literal("resources/subscribe"), params: SubscribeRequestParamsSchema }); var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; var UnsubscribeRequestSchema = RequestSchema.extend({ method: literal("resources/unsubscribe"), params: UnsubscribeRequestParamsSchema }); var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. */ uri: string2() }); var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/updated"), params: ResourceUpdatedNotificationParamsSchema }); var PromptArgumentSchema = object2({ /** * The name of the argument. */ name: string2(), /** * A human-readable description of the argument. */ description: optional(string2()), /** * Whether this argument must be provided. */ required: optional(boolean2()) }); var PromptSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * An optional description of what this prompt provides */ description: optional(string2()), /** * A list of arguments to use for templating the prompt. */ arguments: optional(array(PromptArgumentSchema)), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The name of the prompt or prompt template. */ name: string2(), /** * Arguments to use for templating the prompt. */ arguments: record(string2(), string2()).optional() }); var GetPromptRequestSchema = RequestSchema.extend({ method: literal("prompts/get"), params: GetPromptRequestParamsSchema }); var TextContentSchema = object2({ type: literal("text"), /** * The text content of the message. */ text: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ImageContentSchema = object2({ type: literal("image"), /** * The base64-encoded image data. */ data: Base64Schema, /** * The MIME type of the image. Different providers may support different image types. */ mimeType: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var AudioContentSchema = object2({ type: literal("audio"), /** * The base64-encoded audio data. */ data: Base64Schema, /** * The MIME type of the audio. Different providers may support different audio types. */ mimeType: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ToolUseContentSchema = object2({ type: literal("tool_use"), /** * The name of the tool to invoke. * Must match a tool name from the request's tools array. */ name: string2(), /** * Unique identifier for this tool call. * Used to correlate with ToolResultContent in subsequent messages. */ id: string2(), /** * Arguments to pass to the tool. * Must conform to the tool's inputSchema. */ input: record(string2(), unknown()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var EmbeddedResourceSchema = object2({ type: literal("resource"), resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); var ContentBlockSchema = union([ TextContentSchema, ImageContentSchema, AudioContentSchema, ResourceLinkSchema, EmbeddedResourceSchema ]); var PromptMessageSchema = object2({ role: RoleSchema, content: ContentBlockSchema }); var GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ description: string2().optional(), messages: array(PromptMessageSchema) }); var PromptListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/prompts/list_changed"), params: NotificationsParamsSchema.optional() }); var ToolAnnotationsSchema = object2({ /** * A human-readable title for the tool. */ title: string2().optional(), /** * If true, the tool does not modify its environment. * * Default: false */ readOnlyHint: boolean2().optional(), /** * If true, the tool may perform destructive updates to its environment. * If false, the tool performs only additive updates. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: true */ destructiveHint: boolean2().optional(), /** * If true, calling the tool repeatedly with the same arguments * will have no additional effect on the its environment. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: false */ idempotentHint: boolean2().optional(), /** * If true, this tool may interact with an "open world" of external * entities. If false, the tool's domain of interaction is closed. * For example, the world of a web search tool is open, whereas that * of a memory tool is not. * * Default: true */ openWorldHint: boolean2().optional() }); var ToolExecutionSchema = object2({ /** * Indicates the tool's preference for task-augmented execution. * - "required": Clients MUST invoke the tool as a task * - "optional": Clients MAY invoke the tool as a task or normal request * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task * * If not present, defaults to "forbidden". */ taskSupport: _enum2(["required", "optional", "forbidden"]).optional() }); var ToolSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A human-readable description of the tool. */ description: string2().optional(), /** * A JSON Schema 2020-12 object defining the expected parameters for the tool. * Must have type: 'object' at the root level per MCP spec. */ inputSchema: object2({ type: literal("object"), properties: record(string2(), AssertObjectSchema).optional(), required: array(string2()).optional() }).catchall(unknown()), /** * An optional JSON Schema 2020-12 object defining the structure of the tool's output * returned in the structuredContent field of a CallToolResult. * Must have type: 'object' at the root level per MCP spec. */ outputSchema: object2({ type: literal("object"), properties: record(string2(), AssertObjectSchema).optional(), required: array(string2()).optional() }).catchall(unknown()).optional(), /** * Optional additional tool information. */ annotations: ToolAnnotationsSchema.optional(), /** * Execution-related properties for this tool. */ execution: ToolExecutionSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); var CallToolResultSchema = ResultSchema.extend({ /** * A list of content objects that represent the result of the tool call. * * If the Tool does not define an outputSchema, this field MUST be present in the result. * For backwards compatibility, this field is always present, but it may be empty. */ content: array(ContentBlockSchema).default([]), /** * An object containing structured tool output. * * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ structuredContent: record(string2(), unknown()).optional(), /** * Whether the tool call ended in an error. * * If not set, this is assumed to be false (the call was successful). * * Any errors that originate from the tool SHOULD be reported inside the result * object, with `isError` set to true, _not_ as an MCP protocol-level error * response. Otherwise, the LLM would not be able to see that an error occurred * and self-correct. * * However, any errors in _finding_ the tool, an error indicating that the * server does not support tool calls, or any other exceptional conditions, * should be reported as an MCP error response. */ isError: boolean2().optional() }); var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The name of the tool to call. */ name: string2(), /** * Arguments to pass to the tool. */ arguments: record(string2(), unknown()).optional() }); var CallToolRequestSchema = RequestSchema.extend({ method: literal("tools/call"), params: CallToolRequestParamsSchema }); var ToolListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tools/list_changed"), params: NotificationsParamsSchema.optional() }); var ListChangedOptionsBaseSchema = object2({ /** * If true, the list will be refreshed automatically when a list changed notification is received. * The callback will be called with the updated list. * * If false, the callback will be called with null items, allowing manual refresh. * * @default true */ autoRefresh: boolean2().default(true), /** * Debounce time in milliseconds for list changed notification processing. * * Multiple notifications received within this timeframe will only trigger one refresh. * Set to 0 to disable debouncing. * * @default 300 */ debounceMs: number2().int().nonnegative().default(300) }); var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. */ level: LoggingLevelSchema }); var SetLevelRequestSchema = RequestSchema.extend({ method: literal("logging/setLevel"), params: SetLevelRequestParamsSchema }); var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The severity of this log message. */ level: LoggingLevelSchema, /** * An optional name of the logger issuing this message. */ logger: string2().optional(), /** * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. */ data: unknown() }); var LoggingMessageNotificationSchema = NotificationSchema.extend({ method: literal("notifications/message"), params: LoggingMessageNotificationParamsSchema }); var ModelHintSchema = object2({ /** * A hint for a model name. */ name: string2().optional() }); var ModelPreferencesSchema = object2({ /** * Optional hints to use for model selection. */ hints: array(ModelHintSchema).optional(), /** * How much to prioritize cost when selecting a model. */ costPriority: number2().min(0).max(1).optional(), /** * How much to prioritize sampling speed (latency) when selecting a model. */ speedPriority: number2().min(0).max(1).optional(), /** * How much to prioritize intelligence and capabilities when selecting a model. */ intelligencePriority: number2().min(0).max(1).optional() }); var ToolChoiceSchema = object2({ /** * Controls when tools are used: * - "auto": Model decides whether to use tools (default) * - "required": Model MUST use at least one tool before completing * - "none": Model MUST NOT use any tools */ mode: _enum2(["auto", "required", "none"]).optional() }); var ToolResultContentSchema = object2({ type: literal("tool_result"), toolUseId: string2().describe("The unique identifier for the corresponding tool call."), content: array(ContentBlockSchema).default([]), structuredContent: object2({}).loose().optional(), isError: boolean2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, ToolResultContentSchema ]); var SamplingMessageSchema = object2({ role: RoleSchema, content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: array(SamplingMessageSchema), /** * The server's preferences for which model to select. The client MAY modify or omit this request. */ modelPreferences: ModelPreferencesSchema.optional(), /** * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. */ systemPrompt: string2().optional(), /** * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. * The client MAY ignore this request. * * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. */ includeContext: _enum2(["none", "thisServer", "allServers"]).optional(), temperature: number2().optional(), /** * The requested maximum number of tokens to sample (to prevent runaway completions). * * The client MAY choose to sample fewer tokens than the requested maximum. */ maxTokens: number2().int(), stopSequences: array(string2()).optional(), /** * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. */ metadata: AssertObjectSchema.optional(), /** * Tools that the model may use during generation. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. */ tools: array(ToolSchema).optional(), /** * Controls how the model uses tools. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * Default is `{ mode: "auto" }`. */ toolChoice: ToolChoiceSchema.optional() }); var CreateMessageRequestSchema = RequestSchema.extend({ method: literal("sampling/createMessage"), params: CreateMessageRequestParamsSchema }); var CreateMessageResultSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: string2(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string2())), role: RoleSchema, /** * Response content. Single content block (text, image, or audio). */ content: SamplingContentSchema }); var CreateMessageResultWithToolsSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: string2(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * - "toolUse": The model wants to use one or more tools * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), role: RoleSchema, /** * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". */ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) }); var BooleanSchemaSchema = object2({ type: literal("boolean"), title: string2().optional(), description: string2().optional(), default: boolean2().optional() }); var StringSchemaSchema = object2({ type: literal("string"), title: string2().optional(), description: string2().optional(), minLength: number2().optional(), maxLength: number2().optional(), format: _enum2(["email", "uri", "date", "date-time"]).optional(), default: string2().optional() }); var NumberSchemaSchema = object2({ type: _enum2(["number", "integer"]), title: string2().optional(), description: string2().optional(), minimum: number2().optional(), maximum: number2().optional(), default: number2().optional() }); var UntitledSingleSelectEnumSchemaSchema = object2({ type: literal("string"), title: string2().optional(), description: string2().optional(), enum: array(string2()), default: string2().optional() }); var TitledSingleSelectEnumSchemaSchema = object2({ type: literal("string"), title: string2().optional(), description: string2().optional(), oneOf: array(object2({ const: string2(), title: string2() })), default: string2().optional() }); var LegacyTitledEnumSchemaSchema = object2({ type: literal("string"), title: string2().optional(), description: string2().optional(), enum: array(string2()), enumNames: array(string2()).optional(), default: string2().optional() }); var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); var UntitledMultiSelectEnumSchemaSchema = object2({ type: literal("array"), title: string2().optional(), description: string2().optional(), minItems: number2().optional(), maxItems: number2().optional(), items: object2({ type: literal("string"), enum: array(string2()) }), default: array(string2()).optional() }); var TitledMultiSelectEnumSchemaSchema = object2({ type: literal("array"), title: string2().optional(), description: string2().optional(), minItems: number2().optional(), maxItems: number2().optional(), items: object2({ anyOf: array(object2({ const: string2(), title: string2() })) }), default: array(string2()).optional() }); var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. * * Optional for backward compatibility. Clients MUST treat missing mode as "form". */ mode: literal("form").optional(), /** * The message to present to the user describing what information is being requested. */ message: string2(), /** * A restricted subset of JSON Schema. * Only top-level properties are allowed, without nesting. */ requestedSchema: object2({ type: literal("object"), properties: record(string2(), PrimitiveSchemaDefinitionSchema), required: array(string2()).optional() }) }); var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. */ mode: literal("url"), /** * The message to present to the user explaining why the interaction is needed. */ message: string2(), /** * The ID of the elicitation, which must be unique within the context of the server. * The client MUST treat this ID as an opaque value. */ elicitationId: string2(), /** * The URL that the user should navigate to. */ url: string2().url() }); var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); var ElicitRequestSchema = RequestSchema.extend({ method: literal("elicitation/create"), params: ElicitRequestParamsSchema }); var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the elicitation that completed. */ elicitationId: string2() }); var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ method: literal("notifications/elicitation/complete"), params: ElicitationCompleteNotificationParamsSchema }); var ElicitResultSchema = ResultSchema.extend({ /** * The user action in response to the elicitation. * - "accept": User submitted the form/confirmed the action * - "decline": User explicitly decline the action * - "cancel": User dismissed without making an explicit choice */ action: _enum2(["accept", "decline", "cancel"]), /** * The submitted form data, only present when action is "accept". * Contains values matching the requested schema. * Per MCP spec, content is "typically omitted" for decline/cancel actions. * We normalize null to undefined for leniency while maintaining type compatibility. */ content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) }); var ResourceTemplateReferenceSchema = object2({ type: literal("ref/resource"), /** * The URI or URI template of the resource. */ uri: string2() }); var PromptReferenceSchema = object2({ type: literal("ref/prompt"), /** * The name of the prompt or prompt template */ name: string2() }); var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), /** * The argument's information */ argument: object2({ /** * The name of the argument */ name: string2(), /** * The value of the argument to use for completion matching. */ value: string2() }), context: object2({ /** * Previously-resolved variables in a URI template or prompt. */ arguments: record(string2(), string2()).optional() }).optional() }); var CompleteRequestSchema = RequestSchema.extend({ method: literal("completion/complete"), params: CompleteRequestParamsSchema }); function assertCompleteRequestPrompt(request) { if (request.params.ref.type !== "ref/prompt") { throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); } void request; } function assertCompleteRequestResourceTemplate(request) { if (request.params.ref.type !== "ref/resource") { throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); } void request; } var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ /** * An array of completion values. Must not exceed 100 items. */ values: array(string2()).max(100), /** * The total number of completion options available. This can exceed the number of values actually sent in the response. */ total: optional(number2().int()), /** * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. */ hasMore: optional(boolean2()) }) }); var RootSchema = object2({ /** * The URI identifying the root. This *must* start with file:// for now. */ uri: string2().startsWith("file://"), /** * An optional name for the root. */ name: string2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ListRootsRequestSchema = RequestSchema.extend({ method: literal("roots/list"), params: BaseRequestParamsSchema.optional() }); var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); var RootsListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/roots/list_changed"), params: NotificationsParamsSchema.optional() }); var ClientRequestSchema = union([ PingRequestSchema, InitializeRequestSchema, CompleteRequestSchema, SetLevelRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, CallToolRequestSchema, ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); var ClientNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, InitializedNotificationSchema, RootsListChangedNotificationSchema, TaskStatusNotificationSchema ]); var ClientResultSchema = union([ EmptyResultSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, ListRootsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); var ServerRequestSchema = union([ PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); var ServerNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, LoggingMessageNotificationSchema, ResourceUpdatedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, TaskStatusNotificationSchema, ElicitationCompleteNotificationSchema ]); var ServerResultSchema = union([ EmptyResultSchema, InitializeResultSchema, CompleteResultSchema, GetPromptResultSchema, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, CallToolResultSchema, ListToolsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); var McpError = class _McpError extends Error { constructor(code, message, data) { super(`MCP error ${code}: ${message}`); this.code = code; this.data = data; this.name = "McpError"; } /** * Factory method to create the appropriate error type based on the error code and data */ static fromError(code, message, data) { if (code === ErrorCode.UrlElicitationRequired && data) { const errorData = data; if (errorData.elicitations) { return new UrlElicitationRequiredError(errorData.elicitations, message); } } return new _McpError(code, message, data); } }; var UrlElicitationRequiredError = class extends McpError { constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { super(ErrorCode.UrlElicitationRequired, message, { elicitations }); } get elicitations() { return this.data?.elicitations ?? []; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js init_define_KSQL_DOCS(); function isTerminal(status) { return status === "completed" || status === "failed" || status === "cancelled"; } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/index.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/Options.js init_define_KSQL_DOCS(); var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use"); var defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", target: "jsonSchema7", strictUnions: false, definitions: {}, errorMessages: false, markdownDescription: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref", openAiAnyTypeName: "OpenAiAnyType" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; // node_modules/zod-to-json-schema/dist/esm/Refs.js init_define_KSQL_DOCS(); var getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, flags: { hasReferencedOpenAiAnyType: false }, currentPath, propertyPath: void 0, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ])) }; }; // node_modules/zod-to-json-schema/dist/esm/errorMessages.js init_define_KSQL_DOCS(); function addErrorMessage(res, key, errorMessage2, refs) { if (!refs?.errorMessages) return; if (errorMessage2) { res.errorMessage = { ...res.errorMessage, [key]: errorMessage2 }; } } function setResponseValueAndErrors(res, key, value, errorMessage2, refs) { res[key] = value; addErrorMessage(res, key, errorMessage2, refs); } // node_modules/zod-to-json-schema/dist/esm/getRelativePath.js init_define_KSQL_DOCS(); var getRelativePath = (pathA, pathB) => { let i = 0; for (; i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; // node_modules/zod-to-json-schema/dist/esm/parseDef.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/selectParser.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/parsers/any.js init_define_KSQL_DOCS(); function parseAnyDef(refs) { if (refs.target !== "openAi") { return {}; } const anyDefinitionPath = [ ...refs.basePath, refs.definitionPath, refs.openAiAnyTypeName ]; refs.flags.hasReferencedOpenAiAnyType = true; return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; } // node_modules/zod-to-json-schema/dist/esm/parsers/array.js init_define_KSQL_DOCS(); function parseArrayDef(def, refs) { const res = { type: "array" }; if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); } if (def.maxLength) { setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } if (def.exactLength) { setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js init_define_KSQL_DOCS(); function parseBigintDef(def, refs) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check2 of def.checks) { switch (check2.kind) { case "min": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); break; } } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js init_define_KSQL_DOCS(); function parseBooleanDef() { return { type: "boolean" }; } // node_modules/zod-to-json-schema/dist/esm/parsers/branded.js init_define_KSQL_DOCS(); function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/catch.js init_define_KSQL_DOCS(); var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; // node_modules/zod-to-json-schema/dist/esm/parsers/date.js init_define_KSQL_DOCS(); function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy ?? refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def, refs); } } var integerDateParser = (def, refs) => { const res = { type: "integer", format: "unix-time" }; if (refs.target === "openApi3") { return res; } for (const check2 of def.checks) { switch (check2.kind) { case "min": setResponseValueAndErrors( res, "minimum", check2.value, // This is in milliseconds check2.message, refs ); break; case "max": setResponseValueAndErrors( res, "maximum", check2.value, // This is in milliseconds check2.message, refs ); break; } } return res; }; // node_modules/zod-to-json-schema/dist/esm/parsers/default.js init_define_KSQL_DOCS(); function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } // node_modules/zod-to-json-schema/dist/esm/parsers/effects.js init_define_KSQL_DOCS(); function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/enum.js init_define_KSQL_DOCS(); function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } // node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js init_define_KSQL_DOCS(); var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); if (schema.unevaluatedProperties === void 0) { unevaluatedProperties = void 0; } } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } else { unevaluatedProperties = void 0; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf, ...unevaluatedProperties } : void 0; } // node_modules/zod-to-json-schema/dist/esm/parsers/literal.js init_define_KSQL_DOCS(); function parseLiteralDef(def, refs) { const parsedType2 = typeof def.value; if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } if (refs.target === "openApi3") { return { type: parsedType2 === "bigint" ? "integer" : parsedType2, enum: [def.value] }; } return { type: parsedType2 === "bigint" ? "integer" : parsedType2, const: def.value }; } // node_modules/zod-to-json-schema/dist/esm/parsers/map.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/parsers/record.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/parsers/string.js init_define_KSQL_DOCS(); var emojiRegex2 = void 0; var zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex2 === void 0) { emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } return emojiRegex2; }, /** * Unused */ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, /** * Unused */ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, /** * Unused */ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check2 of def.checks) { switch (check2.kind) { case "min": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); break; case "max": setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check2.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check2.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check2.message, refs); break; } break; case "url": addFormat(res, "uri", check2.message, refs); break; case "uuid": addFormat(res, "uuid", check2.message, refs); break; case "regex": addPattern(res, check2.regex, check2.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check2.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check2.message, refs); break; case "startsWith": addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs); break; case "endsWith": addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs); break; case "datetime": addFormat(res, "date-time", check2.message, refs); break; case "date": addFormat(res, "date", check2.message, refs); break; case "time": addFormat(res, "time", check2.message, refs); break; case "duration": addFormat(res, "duration", check2.message, refs); break; case "length": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); break; case "includes": { addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs); break; } case "ip": { if (check2.version !== "v6") { addFormat(res, "ipv4", check2.message, refs); } if (check2.version !== "v4") { addFormat(res, "ipv6", check2.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check2.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check2.message, refs); break; case "cidr": { if (check2.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); } if (check2.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check2.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check2.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check2.message, refs); break; } case "contentEncoding:base64": { setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs); break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check2.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check2.message, refs); } case "toLowerCase": case "toUpperCase": case "trim": break; default: /* @__PURE__ */ ((_) => { })(check2); } } } return res; } function escapeLiteralCheckValue(literal2, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; } var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); function escapeNonAlphaNumeric(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat(schema, value, message, refs) { if (schema.format || schema.anyOf?.some((x) => x.format)) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format, ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } }); delete schema.format; if (schema.errorMessage) { delete schema.errorMessage.format; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { setResponseValueAndErrors(schema, "format", value, message, refs); } } function addPattern(schema, regex, message, refs) { if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern, ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } }); delete schema.pattern; if (schema.errorMessage) { delete schema.errorMessage.pattern; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.allOf.push({ pattern: stringifyRegExpWithFlags(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); } } function stringifyRegExpWithFlags(regex, refs) { if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), m: regex.flags.includes("m"), s: regex.flags.includes("s") // `.` matches newlines }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } try { new RegExp(pattern); } catch { console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); return regex.source; } return pattern; } // node_modules/zod-to-json-schema/dist/esm/parsers/record.js function parseRecordDef(def, refs) { if (refs.target === "openAi") { console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); } if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { type: "object", required: def.keyType._def.values, properties: def.keyType._def.values.reduce((acc, key) => ({ ...acc, [key]: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "properties", key] }) ?? parseAnyDef(refs) }), {}), additionalProperties: refs.rejectedAdditionalProperties }; } const schema = { type: "object", additionalProperties: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? refs.allowedAdditionalProperties }; if (refs.target === "openApi3") { return schema; } if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { const { type, ...keyType } = parseStringDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } return schema; } // node_modules/zod-to-json-schema/dist/esm/parsers/map.js function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef(refs); const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef(refs); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } // node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js init_define_KSQL_DOCS(); function parseNativeEnumDef(def) { const object3 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object3[object3[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object3[key]); const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } // node_modules/zod-to-json-schema/dist/esm/parsers/never.js init_define_KSQL_DOCS(); function parseNeverDef(refs) { return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ ...refs, currentPath: [...refs.currentPath, "not"] }) }; } // node_modules/zod-to-json-schema/dist/esm/parsers/null.js init_define_KSQL_DOCS(); function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true } : { type: "null" }; } // node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/parsers/union.js init_define_KSQL_DOCS(); var primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef(def, refs) { if (refs.target === "openApi3") return asAnyOf(def, refs); const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { const types = options.reduce((types2, x) => { const type = primitiveMappings[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce((acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, []); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce((acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, []) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce((acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], []) }; } return asAnyOf(def, refs); } var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`] })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); return anyOf.length ? { anyOf } : void 0; }; // node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { if (refs.target === "openApi3") { return { type: primitiveMappings[def.innerType._def.typeName], nullable: true }; } return { type: [ primitiveMappings[def.innerType._def.typeName], "null" ] }; } if (refs.target === "openApi3") { const base2 = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath] }); if (base2 && "$ref" in base2) return { allOf: [base2], nullable: true }; return base2 && { ...base2, nullable: true }; } const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } // node_modules/zod-to-json-schema/dist/esm/parsers/number.js init_define_KSQL_DOCS(); function parseNumberDef(def, refs) { const res = { type: "number" }; if (!def.checks) return res; for (const check2 of def.checks) { switch (check2.kind) { case "int": res.type = "integer"; addErrorMessage(res, "type", check2.message, refs); break; case "min": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); break; } } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/object.js init_define_KSQL_DOCS(); function parseObjectDef(def, refs) { const forceOptionalIntoNullable = refs.target === "openAi"; const result = { type: "object", properties: {} }; const required2 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } let propOptional = safeIsOptional(propDef); if (propOptional && forceOptionalIntoNullable) { if (propDef._def.typeName === "ZodOptional") { propDef = propDef._def.innerType; } if (!propDef.isNullable()) { propDef = propDef.nullable(); } propOptional = false; } const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required2.push(propName); } } if (required2.length) { result.required = required2; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional(schema) { try { return schema.isOptional(); } catch { return true; } } // node_modules/zod-to-json-schema/dist/esm/parsers/optional.js init_define_KSQL_DOCS(); var parseOptionalDef = (def, refs) => { if (refs.currentPath.toString() === refs.propertyPath?.toString()) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [ { not: parseAnyDef(refs) }, innerSchema ] } : parseAnyDef(refs); }; // node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js init_define_KSQL_DOCS(); var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const a = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; // node_modules/zod-to-json-schema/dist/esm/parsers/promise.js init_define_KSQL_DOCS(); function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/set.js init_define_KSQL_DOCS(); function parseSetDef(def, refs) { const items = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); } if (def.maxSize) { setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); } return schema; } // node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js init_define_KSQL_DOCS(); function parseTupleDef(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), additionalItems: parseDef(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"] }) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) }; } } // node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js init_define_KSQL_DOCS(); function parseUndefinedDef(refs) { return { not: parseAnyDef(refs) }; } // node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js init_define_KSQL_DOCS(); function parseUnknownDef(refs) { return parseAnyDef(refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js init_define_KSQL_DOCS(); var parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; // node_modules/zod-to-json-schema/dist/esm/selectParser.js var selectParser = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); case ZodFirstPartyTypeKind.ZodUnion: case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); case ZodFirstPartyTypeKind.ZodNaN: case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs); case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs); case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs); case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); case ZodFirstPartyTypeKind.ZodFunction: case ZodFirstPartyTypeKind.ZodVoid: case ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(typeName); } }; // node_modules/zod-to-json-schema/dist/esm/parseDef.js function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); if (overrideResult !== ignoreOverride) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema) { addMeta(def, refs, jsonSchema); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema, def, refs); newItem.jsonSchema = jsonSchema; return postProcessResult; } newItem.jsonSchema = jsonSchema; return jsonSchema; } var get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); return parseAnyDef(refs); } return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; } } }; var addMeta = (def, refs, jsonSchema) => { if (def.description) { jsonSchema.description = def.description; if (refs.markdownDescription) { jsonSchema.markdownDescription = def.description; } } return jsonSchema; }; // node_modules/zod-to-json-schema/dist/esm/parseTypes.js init_define_KSQL_DOCS(); // node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js init_define_KSQL_DOCS(); var zodToJsonSchema = (schema, options) => { const refs = getRefs(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ ...acc, [name2]: parseDef(schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name2] }, true) ?? parseAnyDef(refs) }), {}) : void 0; const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; const main2 = parseDef(schema._def, name === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name] }, false) ?? parseAnyDef(refs); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main2.title = title; } if (refs.flags.hasReferencedOpenAiAnyType) { if (!definitions) { definitions = {}; } if (!definitions[refs.openAiAnyTypeName]) { definitions[refs.openAiAnyTypeName] = { // Skipping "object" as no properties can be defined and additionalProperties must be "false" type: ["string", "number", "integer", "boolean", "array", "null"], items: { $ref: refs.$refStrategy === "relative" ? "1" : [ ...refs.basePath, refs.definitionPath, refs.openAiAnyTypeName ].join("/") } }; } } const combined = name === void 0 ? definitions ? { ...main2, [refs.definitionPath]: definitions } : main2 : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name ].join("/"), [refs.definitionPath]: { ...definitions, [name]: main2 } }; if (refs.target === "jsonSchema7") { combined.$schema = "http://json-schema.org/draft-07/schema#"; } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); } return combined; }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js function mapMiniTarget(t) { if (!t) return "draft-7"; if (t === "jsonSchema7" || t === "draft-7") return "draft-7"; if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12"; return "draft-7"; } function toJsonSchemaCompat(schema, opts) { if (isZ4Schema(schema)) { return toJSONSchema(schema, { target: mapMiniTarget(opts?.target), io: opts?.pipeStrategy ?? "input" }); } return zodToJsonSchema(schema, { strictUnions: opts?.strictUnions ?? true, pipeStrategy: opts?.pipeStrategy ?? "input" }); } function getMethodLiteral(schema) { const shape = getObjectShape(schema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error("Schema is missing a method literal"); } const value = getLiteralValue(methodSchema); if (typeof value !== "string") { throw new Error("Schema method literal must be a string"); } return value; } function parseWithCompat(schema, data) { const result = safeParse2(schema, data); if (!result.success) { throw result.error; } return result.data; } // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; var Protocol = class { constructor(_options) { this._options = _options; this._requestMessageId = 0; this._requestHandlers = /* @__PURE__ */ new Map(); this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); this._notificationHandlers = /* @__PURE__ */ new Map(); this._responseHandlers = /* @__PURE__ */ new Map(); this._progressHandlers = /* @__PURE__ */ new Map(); this._timeoutInfo = /* @__PURE__ */ new Map(); this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); this._taskProgressTokens = /* @__PURE__ */ new Map(); this._requestResolvers = /* @__PURE__ */ new Map(); this.setNotificationHandler(CancelledNotificationSchema, (notification) => { this._oncancel(notification); }); this.setNotificationHandler(ProgressNotificationSchema, (notification) => { this._onprogress(notification); }); this.setRequestHandler( PingRequestSchema, // Automatic pong by default. (_request) => ({}) ); this._taskStore = _options?.taskStore; this._taskMessageQueue = _options?.taskMessageQueue; if (this._taskStore) { this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); } return { ...task }; }); this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { const handleTaskResult = async () => { const taskId = request.params.taskId; if (this._taskMessageQueue) { let queuedMessage; while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { if (queuedMessage.type === "response" || queuedMessage.type === "error") { const message = queuedMessage.message; const requestId = message.id; const resolver = this._requestResolvers.get(requestId); if (resolver) { this._requestResolvers.delete(requestId); if (queuedMessage.type === "response") { resolver(message); } else { const errorMessage2 = message; const error51 = new McpError(errorMessage2.error.code, errorMessage2.error.message, errorMessage2.error.data); resolver(error51); } } else { const messageType = queuedMessage.type === "response" ? "Response" : "Error"; this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); } continue; } await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); } } const task = await this._taskStore.getTask(taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); } if (!isTerminal(task.status)) { await this._waitForTaskUpdate(taskId, extra.signal); return await handleTaskResult(); } if (isTerminal(task.status)) { const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); this._clearTaskQueue(taskId); return { ...result, _meta: { ...result._meta, [RELATED_TASK_META_KEY]: { taskId } } }; } return await handleTaskResult(); }; return await handleTaskResult(); }); this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { try { const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); return { tasks, nextCursor, _meta: {} }; } catch (error51) { throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error51 instanceof Error ? error51.message : String(error51)}`); } }); this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { try { const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); } if (isTerminal(task.status)) { throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); } await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); this._clearTaskQueue(request.params.taskId); const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!cancelledTask) { throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); } return { _meta: {}, ...cancelledTask }; } catch (error51) { if (error51 instanceof McpError) { throw error51; } throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error51 instanceof Error ? error51.message : String(error51)}`); } }); } } async _oncancel(notification) { if (!notification.params.requestId) { return; } const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); controller?.abort(notification.params.reason); } _setupTimeout(messageId, timeout2, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { this._timeoutInfo.set(messageId, { timeoutId: setTimeout(onTimeout, timeout2), startTime: Date.now(), timeout: timeout2, maxTotalTimeout, resetTimeoutOnProgress, onTimeout }); } _resetTimeout(messageId) { const info = this._timeoutInfo.get(messageId); if (!info) return false; const totalElapsed = Date.now() - info.startTime; if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { this._timeoutInfo.delete(messageId); throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { maxTotalTimeout: info.maxTotalTimeout, totalElapsed }); } clearTimeout(info.timeoutId); info.timeoutId = setTimeout(info.onTimeout, info.timeout); return true; } _cleanupTimeout(messageId) { const info = this._timeoutInfo.get(messageId); if (info) { clearTimeout(info.timeoutId); this._timeoutInfo.delete(messageId); } } /** * Attaches to the given transport, starts it, and starts listening for messages. * * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. */ async connect(transport) { if (this._transport) { throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); } this._transport = transport; const _onclose = this.transport?.onclose; this._transport.onclose = () => { _onclose?.(); this._onclose(); }; const _onerror = this.transport?.onerror; this._transport.onerror = (error51) => { _onerror?.(error51); this._onerror(error51); }; const _onmessage = this._transport?.onmessage; this._transport.onmessage = (message, extra) => { _onmessage?.(message, extra); if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { this._onrequest(message, extra); } else if (isJSONRPCNotification(message)) { this._onnotification(message); } else { this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); } }; await this._transport.start(); } _onclose() { const responseHandlers = this._responseHandlers; this._responseHandlers = /* @__PURE__ */ new Map(); this._progressHandlers.clear(); this._taskProgressTokens.clear(); this._pendingDebouncedNotifications.clear(); for (const info of this._timeoutInfo.values()) { clearTimeout(info.timeoutId); } this._timeoutInfo.clear(); for (const controller of this._requestHandlerAbortControllers.values()) { controller.abort(); } this._requestHandlerAbortControllers.clear(); const error51 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); this._transport = void 0; this.onclose?.(); for (const handler of responseHandlers.values()) { handler(error51); } } _onerror(error51) { this.onerror?.(error51); } _onnotification(notification) { const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; if (handler === void 0) { return; } Promise.resolve().then(() => handler(notification)).catch((error51) => this._onerror(new Error(`Uncaught error in notification handler: ${error51}`))); } _onrequest(request, extra) { const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; const capturedTransport = this._transport; const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; if (handler === void 0) { const errorResponse = { jsonrpc: "2.0", id: request.id, error: { code: ErrorCode.MethodNotFound, message: "Method not found" } }; if (relatedTaskId && this._taskMessageQueue) { this._enqueueTaskMessage(relatedTaskId, { type: "error", message: errorResponse, timestamp: Date.now() }, capturedTransport?.sessionId).catch((error51) => this._onerror(new Error(`Failed to enqueue error response: ${error51}`))); } else { capturedTransport?.send(errorResponse).catch((error51) => this._onerror(new Error(`Failed to send an error response: ${error51}`))); } return; } const abortController = new AbortController(); this._requestHandlerAbortControllers.set(request.id, abortController); const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; const fullExtra = { signal: abortController.signal, sessionId: capturedTransport?.sessionId, _meta: request.params?._meta, sendNotification: async (notification) => { if (abortController.signal.aborted) return; const notificationOptions = { relatedRequestId: request.id }; if (relatedTaskId) { notificationOptions.relatedTask = { taskId: relatedTaskId }; } await this.notification(notification, notificationOptions); }, sendRequest: async (r, resultSchema, options) => { if (abortController.signal.aborted) { throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); } const requestOptions = { ...options, relatedRequestId: request.id }; if (relatedTaskId && !requestOptions.relatedTask) { requestOptions.relatedTask = { taskId: relatedTaskId }; } const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; if (effectiveTaskId && taskStore) { await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); } return await this.request(r, resultSchema, requestOptions); }, authInfo: extra?.authInfo, requestId: request.id, requestInfo: extra?.requestInfo, taskId: relatedTaskId, taskStore, taskRequestedTtl: taskCreationParams?.ttl, closeSSEStream: extra?.closeSSEStream, closeStandaloneSSEStream: extra?.closeStandaloneSSEStream }; Promise.resolve().then(() => { if (taskCreationParams) { this.assertTaskHandlerCapability(request.method); } }).then(() => handler(request, fullExtra)).then(async (result) => { if (abortController.signal.aborted) { return; } const response = { result, jsonrpc: "2.0", id: request.id }; if (relatedTaskId && this._taskMessageQueue) { await this._enqueueTaskMessage(relatedTaskId, { type: "response", message: response, timestamp: Date.now() }, capturedTransport?.sessionId); } else { await capturedTransport?.send(response); } }, async (error51) => { if (abortController.signal.aborted) { return; } const errorResponse = { jsonrpc: "2.0", id: request.id, error: { code: Number.isSafeInteger(error51["code"]) ? error51["code"] : ErrorCode.InternalError, message: error51.message ?? "Internal error", ...error51["data"] !== void 0 && { data: error51["data"] } } }; if (relatedTaskId && this._taskMessageQueue) { await this._enqueueTaskMessage(relatedTaskId, { type: "error", message: errorResponse, timestamp: Date.now() }, capturedTransport?.sessionId); } else { await capturedTransport?.send(errorResponse); } }).catch((error51) => this._onerror(new Error(`Failed to send response: ${error51}`))).finally(() => { if (this._requestHandlerAbortControllers.get(request.id) === abortController) { this._requestHandlerAbortControllers.delete(request.id); } }); } _onprogress(notification) { const { progressToken, ...params } = notification.params; const messageId = Number(progressToken); const handler = this._progressHandlers.get(messageId); if (!handler) { this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); return; } const responseHandler = this._responseHandlers.get(messageId); const timeoutInfo = this._timeoutInfo.get(messageId); if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { try { this._resetTimeout(messageId); } catch (error51) { this._responseHandlers.delete(messageId); this._progressHandlers.delete(messageId); this._cleanupTimeout(messageId); responseHandler(error51); return; } } handler(params); } _onresponse(response) { const messageId = Number(response.id); const resolver = this._requestResolvers.get(messageId); if (resolver) { this._requestResolvers.delete(messageId); if (isJSONRPCResultResponse(response)) { resolver(response); } else { const error51 = new McpError(response.error.code, response.error.message, response.error.data); resolver(error51); } return; } const handler = this._responseHandlers.get(messageId); if (handler === void 0) { this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); return; } this._responseHandlers.delete(messageId); this._cleanupTimeout(messageId); let isTaskResponse = false; if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { const result = response.result; if (result.task && typeof result.task === "object") { const task = result.task; if (typeof task.taskId === "string") { isTaskResponse = true; this._taskProgressTokens.set(task.taskId, messageId); } } } if (!isTaskResponse) { this._progressHandlers.delete(messageId); } if (isJSONRPCResultResponse(response)) { handler(response); } else { const error51 = McpError.fromError(response.error.code, response.error.message, response.error.data); handler(error51); } } get transport() { return this._transport; } /** * Closes the connection. */ async close() { await this._transport?.close(); } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * @example * ```typescript * const stream = protocol.requestStream(request, resultSchema, options); * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('Final result:', message.result); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @experimental Use `client.experimental.tasks.requestStream()` to access this method. */ async *requestStream(request, resultSchema, options) { const { task } = options ?? {}; if (!task) { try { const result = await this.request(request, resultSchema, options); yield { type: "result", result }; } catch (error51) { yield { type: "error", error: error51 instanceof McpError ? error51 : new McpError(ErrorCode.InternalError, String(error51)) }; } return; } let taskId; try { const createResult = await this.request(request, CreateTaskResultSchema, options); if (createResult.task) { taskId = createResult.task.taskId; yield { type: "taskCreated", task: createResult.task }; } else { throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); } while (true) { const task2 = await this.getTask({ taskId }, options); yield { type: "taskStatus", task: task2 }; if (isTerminal(task2.status)) { if (task2.status === "completed") { const result = await this.getTaskResult({ taskId }, resultSchema, options); yield { type: "result", result }; } else if (task2.status === "failed") { yield { type: "error", error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) }; } else if (task2.status === "cancelled") { yield { type: "error", error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) }; } return; } if (task2.status === "input_required") { const result = await this.getTaskResult({ taskId }, resultSchema, options); yield { type: "result", result }; return; } const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; await new Promise((resolve3) => setTimeout(resolve3, pollInterval)); options?.signal?.throwIfAborted(); } } catch (error51) { yield { type: "error", error: error51 instanceof McpError ? error51 : new McpError(ErrorCode.InternalError, String(error51)) }; } } /** * Sends a request and waits for a response. * * Do not use this method to emit notifications! Use notification() instead. */ request(request, resultSchema, options) { const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; return new Promise((resolve3, reject) => { const earlyReject = (error51) => { reject(error51); }; if (!this._transport) { earlyReject(new Error("Not connected")); return; } if (this._options?.enforceStrictCapabilities === true) { try { this.assertCapabilityForMethod(request.method); if (task) { this.assertTaskCapability(request.method); } } catch (e) { earlyReject(e); return; } } options?.signal?.throwIfAborted(); const messageId = this._requestMessageId++; const jsonrpcRequest = { ...request, jsonrpc: "2.0", id: messageId }; if (options?.onprogress) { this._progressHandlers.set(messageId, options.onprogress); jsonrpcRequest.params = { ...request.params, _meta: { ...request.params?._meta || {}, progressToken: messageId } }; } if (task) { jsonrpcRequest.params = { ...jsonrpcRequest.params, task }; } if (relatedTask) { jsonrpcRequest.params = { ...jsonrpcRequest.params, _meta: { ...jsonrpcRequest.params?._meta || {}, [RELATED_TASK_META_KEY]: relatedTask } }; } const cancel = (reason) => { this._responseHandlers.delete(messageId); this._progressHandlers.delete(messageId); this._cleanupTimeout(messageId); this._transport?.send({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: messageId, reason: String(reason) } }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error52) => this._onerror(new Error(`Failed to send cancellation: ${error52}`))); const error51 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); reject(error51); }; this._responseHandlers.set(messageId, (response) => { if (options?.signal?.aborted) { return; } if (response instanceof Error) { return reject(response); } try { const parseResult = safeParse2(resultSchema, response.result); if (!parseResult.success) { reject(parseResult.error); } else { resolve3(parseResult.data); } } catch (error51) { reject(error51); } }); options?.signal?.addEventListener("abort", () => { cancel(options?.signal?.reason); }); const timeout2 = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout: timeout2 })); this._setupTimeout(messageId, timeout2, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); const relatedTaskId = relatedTask?.taskId; if (relatedTaskId) { const responseResolver = (response) => { const handler = this._responseHandlers.get(messageId); if (handler) { handler(response); } else { this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); } }; this._requestResolvers.set(messageId, responseResolver); this._enqueueTaskMessage(relatedTaskId, { type: "request", message: jsonrpcRequest, timestamp: Date.now() }).catch((error51) => { this._cleanupTimeout(messageId); reject(error51); }); } else { this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error51) => { this._cleanupTimeout(messageId); reject(error51); }); } }); } /** * Gets the current status of a task. * * @experimental Use `client.experimental.tasks.getTask()` to access this method. */ async getTask(params, options) { return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); } /** * Retrieves the result of a completed task. * * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. */ async getTaskResult(params, resultSchema, options) { return this.request({ method: "tasks/result", params }, resultSchema, options); } /** * Lists tasks, optionally starting from a pagination cursor. * * @experimental Use `client.experimental.tasks.listTasks()` to access this method. */ async listTasks(params, options) { return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); } /** * Cancels a specific task. * * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. */ async cancelTask(params, options) { return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); } /** * Emits a notification, which is a one-way message that does not expect a response. */ async notification(notification, options) { if (!this._transport) { throw new Error("Not connected"); } this.assertNotificationCapability(notification.method); const relatedTaskId = options?.relatedTask?.taskId; if (relatedTaskId) { const jsonrpcNotification2 = { ...notification, jsonrpc: "2.0", params: { ...notification.params, _meta: { ...notification.params?._meta || {}, [RELATED_TASK_META_KEY]: options.relatedTask } } }; await this._enqueueTaskMessage(relatedTaskId, { type: "notification", message: jsonrpcNotification2, timestamp: Date.now() }); return; } const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; if (canDebounce) { if (this._pendingDebouncedNotifications.has(notification.method)) { return; } this._pendingDebouncedNotifications.add(notification.method); Promise.resolve().then(() => { this._pendingDebouncedNotifications.delete(notification.method); if (!this._transport) { return; } let jsonrpcNotification2 = { ...notification, jsonrpc: "2.0" }; if (options?.relatedTask) { jsonrpcNotification2 = { ...jsonrpcNotification2, params: { ...jsonrpcNotification2.params, _meta: { ...jsonrpcNotification2.params?._meta || {}, [RELATED_TASK_META_KEY]: options.relatedTask } } }; } this._transport?.send(jsonrpcNotification2, options).catch((error51) => this._onerror(error51)); }); return; } let jsonrpcNotification = { ...notification, jsonrpc: "2.0" }; if (options?.relatedTask) { jsonrpcNotification = { ...jsonrpcNotification, params: { ...jsonrpcNotification.params, _meta: { ...jsonrpcNotification.params?._meta || {}, [RELATED_TASK_META_KEY]: options.relatedTask } } }; } await this._transport.send(jsonrpcNotification, options); } /** * Registers a handler to invoke when this protocol object receives a request with the given method. * * Note that this will replace any previous request handler for the same method. */ setRequestHandler(requestSchema, handler) { const method = getMethodLiteral(requestSchema); this.assertRequestHandlerCapability(method); this._requestHandlers.set(method, (request, extra) => { const parsed = parseWithCompat(requestSchema, request); return Promise.resolve(handler(parsed, extra)); }); } /** * Removes the request handler for the given method. */ removeRequestHandler(method) { this._requestHandlers.delete(method); } /** * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. */ assertCanSetRequestHandler(method) { if (this._requestHandlers.has(method)) { throw new Error(`A request handler for ${method} already exists, which would be overridden`); } } /** * Registers a handler to invoke when this protocol object receives a notification with the given method. * * Note that this will replace any previous notification handler for the same method. */ setNotificationHandler(notificationSchema, handler) { const method = getMethodLiteral(notificationSchema); this._notificationHandlers.set(method, (notification) => { const parsed = parseWithCompat(notificationSchema, notification); return Promise.resolve(handler(parsed)); }); } /** * Removes the notification handler for the given method. */ removeNotificationHandler(method) { this._notificationHandlers.delete(method); } /** * Cleans up the progress handler associated with a task. * This should be called when a task reaches a terminal status. */ _cleanupTaskProgressHandler(taskId) { const progressToken = this._taskProgressTokens.get(taskId); if (progressToken !== void 0) { this._progressHandlers.delete(progressToken); this._taskProgressTokens.delete(taskId); } } /** * Enqueues a task-related message for side-channel delivery via tasks/result. * @param taskId The task ID to associate the message with * @param message The message to enqueue * @param sessionId Optional session ID for binding the operation to a specific session * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) * * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer * simply propagates the error. */ async _enqueueTaskMessage(taskId, message, sessionId) { if (!this._taskStore || !this._taskMessageQueue) { throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); } const maxQueueSize = this._options?.maxTaskQueueSize; await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); } /** * Clears the message queue for a task and rejects any pending request resolvers. * @param taskId The task ID whose queue should be cleared * @param sessionId Optional session ID for binding the operation to a specific session */ async _clearTaskQueue(taskId, sessionId) { if (this._taskMessageQueue) { const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); for (const message of messages) { if (message.type === "request" && isJSONRPCRequest(message.message)) { const requestId = message.message.id; const resolver = this._requestResolvers.get(requestId); if (resolver) { resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); this._requestResolvers.delete(requestId); } else { this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); } } } } } /** * Waits for a task update (new messages or status change) with abort signal support. * Uses polling to check for updates at the task's configured poll interval. * @param taskId The task ID to wait for * @param signal Abort signal to cancel the wait * @returns Promise that resolves when an update occurs or rejects if aborted */ async _waitForTaskUpdate(taskId, signal) { let interval = this._options?.defaultTaskPollInterval ?? 1e3; try { const task = await this._taskStore?.getTask(taskId); if (task?.pollInterval) { interval = task.pollInterval; } } catch { } return new Promise((resolve3, reject) => { if (signal.aborted) { reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); return; } const timeoutId = setTimeout(resolve3, interval); signal.addEventListener("abort", () => { clearTimeout(timeoutId); reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); }, { once: true }); }); } requestTaskStore(request, sessionId) { const taskStore = this._taskStore; if (!taskStore) { throw new Error("No task store configured"); } return { createTask: async (taskParams) => { if (!request) { throw new Error("No request provided"); } return await taskStore.createTask(taskParams, request.id, { method: request.method, params: request.params }, sessionId); }, getTask: async (taskId) => { const task = await taskStore.getTask(taskId, sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); } return task; }, storeTaskResult: async (taskId, status, result) => { await taskStore.storeTaskResult(taskId, status, result, sessionId); const task = await taskStore.getTask(taskId, sessionId); if (task) { const notification = TaskStatusNotificationSchema.parse({ method: "notifications/tasks/status", params: task }); await this.notification(notification); if (isTerminal(task.status)) { this._cleanupTaskProgressHandler(taskId); } } }, getTaskResult: (taskId) => { return taskStore.getTaskResult(taskId, sessionId); }, updateTaskStatus: async (taskId, status, statusMessage) => { const task = await taskStore.getTask(taskId, sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); } if (isTerminal(task.status)) { throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); } await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); const updatedTask = await taskStore.getTask(taskId, sessionId); if (updatedTask) { const notification = TaskStatusNotificationSchema.parse({ method: "notifications/tasks/status", params: updatedTask }); await this.notification(notification); if (isTerminal(updatedTask.status)) { this._cleanupTaskProgressHandler(taskId); } } }, listTasks: (cursor) => { return taskStore.listTasks(cursor, sessionId); } }; } }; function isPlainObject2(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function mergeCapabilities(base, additional) { const result = { ...base }; for (const key in additional) { const k = key; const addValue = additional[k]; if (addValue === void 0) continue; const baseValue = result[k]; if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { result[k] = { ...baseValue, ...addValue }; } else { result[k] = addValue; } } return result; } // node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js init_define_KSQL_DOCS(); var import_ajv = __toESM(require_ajv(), 1); var import_ajv_formats = __toESM(require_dist(), 1); function createDefaultAjvInstance() { const ajv = new import_ajv.default({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); const addFormats = import_ajv_formats.default; addFormats(ajv); return ajv; } var AjvJsonSchemaValidator = class { /** * Create an AJV validator * * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. * * @example * ```typescript * // Use default configuration (recommended for most cases) * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; * const validator = new AjvJsonSchemaValidator(); * * // Or provide custom AJV instance for advanced configuration * import { Ajv } from 'ajv'; * import addFormats from 'ajv-formats'; * * const ajv = new Ajv({ validateFormats: true }); * addFormats(ajv); * const validator = new AjvJsonSchemaValidator(ajv); * ``` */ constructor(ajv) { this._ajv = ajv ?? createDefaultAjvInstance(); } /** * Create a validator for the given JSON Schema * * The validator is compiled once and can be reused multiple times. * If the schema has an $id, it will be cached by AJV automatically. * * @param schema - Standard JSON Schema object * @returns A validator function that validates input data */ getValidator(schema) { const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema); return (input) => { const valid = ajvValidator(input); if (valid) { return { valid: true, data: input, errorMessage: void 0 }; } else { return { valid: false, data: void 0, errorMessage: this._ajv.errorsText(ajvValidator.errors) }; } }; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js init_define_KSQL_DOCS(); var ExperimentalServerTasks = class { constructor(_server) { this._server = _server; } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * This method provides streaming access to request processing, allowing you to * observe intermediate task status updates for task-augmented requests. * * @param request - The request to send * @param resultSchema - Zod schema for validating the result * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ requestStream(request, resultSchema, options) { return this._server.requestStream(request, resultSchema, options); } /** * Sends a sampling request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages * before the final result. * * @example * ```typescript * const stream = server.experimental.tasks.createMessageStream({ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], * maxTokens: 100 * }, { * onprogress: (progress) => { * // Handle streaming tokens via progress notifications * console.log('Progress:', progress.message); * } * }); * * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('Final result:', message.result); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @param params - The sampling request parameters * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ createMessageStream(params, options) { const clientCapabilities = this._server.getClientCapabilities(); if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { throw new Error("Client does not support sampling tools capability."); } if (params.messages.length > 0) { const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some((c) => c.type === "tool_result"); const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); if (hasToolResults) { if (lastContent.some((c) => c.type !== "tool_result")) { throw new Error("The last message must contain only tool_result content if any is present"); } if (!hasPreviousToolUse) { throw new Error("tool_result blocks are not matching any tool_use from the previous message"); } } if (hasPreviousToolUse) { const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); } } } return this.requestStream({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); } /** * Sends an elicitation request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' * and 'taskStatus' messages before the final result. * * @example * ```typescript * const stream = server.experimental.tasks.elicitInputStream({ * mode: 'url', * message: 'Please authenticate', * elicitationId: 'auth-123', * url: 'https://example.com/auth' * }, { * task: { ttl: 300000 } // Task-augmented for long-running auth flow * }); * * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('User action:', message.result.action); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @param params - The elicitation request parameters * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ elicitInputStream(params, options) { const clientCapabilities = this._server.getClientCapabilities(); const mode = params.mode ?? "form"; switch (mode) { case "url": { if (!clientCapabilities?.elicitation?.url) { throw new Error("Client does not support url elicitation."); } break; } case "form": { if (!clientCapabilities?.elicitation?.form) { throw new Error("Client does not support form elicitation."); } break; } } const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params; return this.requestStream({ method: "elicitation/create", params: normalizedParams }, ElicitResultSchema, options); } /** * Gets the current status of a task. * * @param taskId - The task identifier * @param options - Optional request options * @returns The task status * * @experimental */ async getTask(taskId, options) { return this._server.getTask({ taskId }, options); } /** * Retrieves the result of a completed task. * * @param taskId - The task identifier * @param resultSchema - Zod schema for validating the result * @param options - Optional request options * @returns The task result * * @experimental */ async getTaskResult(taskId, resultSchema, options) { return this._server.getTaskResult({ taskId }, resultSchema, options); } /** * Lists tasks with optional pagination. * * @param cursor - Optional pagination cursor * @param options - Optional request options * @returns List of tasks with optional next cursor * * @experimental */ async listTasks(cursor, options) { return this._server.listTasks(cursor ? { cursor } : void 0, options); } /** * Cancels a running task. * * @param taskId - The task identifier * @param options - Optional request options * * @experimental */ async cancelTask(taskId, options) { return this._server.cancelTask({ taskId }, options); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js init_define_KSQL_DOCS(); function assertToolsCallTaskCapability(requests, method, entityName) { if (!requests) { throw new Error(`${entityName} does not support task creation (required for ${method})`); } switch (method) { case "tools/call": if (!requests.tools?.call) { throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); } break; default: break; } } function assertClientRequestTaskCapability(requests, method, entityName) { if (!requests) { throw new Error(`${entityName} does not support task creation (required for ${method})`); } switch (method) { case "sampling/createMessage": if (!requests.sampling?.createMessage) { throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); } break; case "elicitation/create": if (!requests.elicitation?.create) { throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); } break; default: break; } } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js var Server = class extends Protocol { /** * Initializes this server with the given name and version information. */ constructor(_serverInfo, options) { super(options); this._serverInfo = _serverInfo; this._loggingLevels = /* @__PURE__ */ new Map(); this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); this.isMessageIgnored = (level, sessionId) => { const currentLevel = this._loggingLevels.get(sessionId); return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; }; this._capabilities = options?.capabilities ?? {}; this._instructions = options?.instructions; this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); if (this._capabilities.logging) { this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0; const { level } = request.params; const parseResult = LoggingLevelSchema.safeParse(level); if (parseResult.success) { this._loggingLevels.set(transportSessionId, parseResult.data); } return {}; }); } } /** * Access experimental features. * * WARNING: These APIs are experimental and may change without notice. * * @experimental */ get experimental() { if (!this._experimental) { this._experimental = { tasks: new ExperimentalServerTasks(this) }; } return this._experimental; } /** * Registers new capabilities. This can only be called before connecting to a transport. * * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). */ registerCapabilities(capabilities) { if (this.transport) { throw new Error("Cannot register capabilities after connecting to transport"); } this._capabilities = mergeCapabilities(this._capabilities, capabilities); } /** * Override request handler registration to enforce server-side validation for tools/call. */ setRequestHandler(requestSchema, handler) { const shape = getObjectShape(requestSchema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error("Schema is missing a method literal"); } let methodValue; if (isZ4Schema(methodSchema)) { const v4Schema = methodSchema; const v4Def = v4Schema._zod?.def; methodValue = v4Def?.value ?? v4Schema.value; } else { const v3Schema = methodSchema; const legacyDef = v3Schema._def; methodValue = legacyDef?.value ?? v3Schema.value; } if (typeof methodValue !== "string") { throw new Error("Schema method literal must be a string"); } const method = methodValue; if (method === "tools/call") { const wrappedHandler = async (request, extra) => { const validatedRequest = safeParse2(CallToolRequestSchema, request); if (!validatedRequest.success) { const errorMessage2 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage2}`); } const { params } = validatedRequest.data; const result = await Promise.resolve(handler(request, extra)); if (params.task) { const taskValidationResult = safeParse2(CreateTaskResultSchema, result); if (!taskValidationResult.success) { const errorMessage2 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage2}`); } return taskValidationResult.data; } const validationResult = safeParse2(CallToolResultSchema, result); if (!validationResult.success) { const errorMessage2 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage2}`); } return validationResult.data; }; return super.setRequestHandler(requestSchema, wrappedHandler); } return super.setRequestHandler(requestSchema, handler); } assertCapabilityForMethod(method) { switch (method) { case "sampling/createMessage": if (!this._clientCapabilities?.sampling) { throw new Error(`Client does not support sampling (required for ${method})`); } break; case "elicitation/create": if (!this._clientCapabilities?.elicitation) { throw new Error(`Client does not support elicitation (required for ${method})`); } break; case "roots/list": if (!this._clientCapabilities?.roots) { throw new Error(`Client does not support listing roots (required for ${method})`); } break; case "ping": break; } } assertNotificationCapability(method) { switch (method) { case "notifications/message": if (!this._capabilities.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case "notifications/resources/updated": case "notifications/resources/list_changed": if (!this._capabilities.resources) { throw new Error(`Server does not support notifying about resources (required for ${method})`); } break; case "notifications/tools/list_changed": if (!this._capabilities.tools) { throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); } break; case "notifications/prompts/list_changed": if (!this._capabilities.prompts) { throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); } break; case "notifications/elicitation/complete": if (!this._clientCapabilities?.elicitation?.url) { throw new Error(`Client does not support URL elicitation (required for ${method})`); } break; case "notifications/cancelled": break; case "notifications/progress": break; } } assertRequestHandlerCapability(method) { if (!this._capabilities) { return; } switch (method) { case "completion/complete": if (!this._capabilities.completions) { throw new Error(`Server does not support completions (required for ${method})`); } break; case "logging/setLevel": if (!this._capabilities.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case "prompts/get": case "prompts/list": if (!this._capabilities.prompts) { throw new Error(`Server does not support prompts (required for ${method})`); } break; case "resources/list": case "resources/templates/list": case "resources/read": if (!this._capabilities.resources) { throw new Error(`Server does not support resources (required for ${method})`); } break; case "tools/call": case "tools/list": if (!this._capabilities.tools) { throw new Error(`Server does not support tools (required for ${method})`); } break; case "tasks/get": case "tasks/list": case "tasks/result": case "tasks/cancel": if (!this._capabilities.tasks) { throw new Error(`Server does not support tasks capability (required for ${method})`); } break; case "ping": case "initialize": break; } } assertTaskCapability(method) { assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client"); } assertTaskHandlerCapability(method) { if (!this._capabilities) { return; } assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server"); } async _oninitialize(request) { const requestedVersion = request.params.protocolVersion; this._clientCapabilities = request.params.capabilities; this._clientVersion = request.params.clientInfo; const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; return { protocolVersion, capabilities: this.getCapabilities(), serverInfo: this._serverInfo, ...this._instructions && { instructions: this._instructions } }; } /** * After initialization has completed, this will be populated with the client's reported capabilities. */ getClientCapabilities() { return this._clientCapabilities; } /** * After initialization has completed, this will be populated with information about the client's name and version. */ getClientVersion() { return this._clientVersion; } getCapabilities() { return this._capabilities; } async ping() { return this.request({ method: "ping" }, EmptyResultSchema); } // Implementation async createMessage(params, options) { if (params.tools || params.toolChoice) { if (!this._clientCapabilities?.sampling?.tools) { throw new Error("Client does not support sampling tools capability."); } } if (params.messages.length > 0) { const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some((c) => c.type === "tool_result"); const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); if (hasToolResults) { if (lastContent.some((c) => c.type !== "tool_result")) { throw new Error("The last message must contain only tool_result content if any is present"); } if (!hasPreviousToolUse) { throw new Error("tool_result blocks are not matching any tool_use from the previous message"); } } if (hasPreviousToolUse) { const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); } } } if (params.tools) { return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options); } return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); } /** * Creates an elicitation request for the given parameters. * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. * @param params The parameters for the elicitation request. * @param options Optional request options. * @returns The result of the elicitation request. */ async elicitInput(params, options) { const mode = params.mode ?? "form"; switch (mode) { case "url": { if (!this._clientCapabilities?.elicitation?.url) { throw new Error("Client does not support url elicitation."); } const urlParams = params; return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options); } case "form": { if (!this._clientCapabilities?.elicitation?.form) { throw new Error("Client does not support form elicitation."); } const formParams = params.mode === "form" ? params : { ...params, mode: "form" }; const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options); if (result.action === "accept" && result.content && formParams.requestedSchema) { try { const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); const validationResult = validator(result.content); if (!validationResult.valid) { throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); } } catch (error51) { if (error51 instanceof McpError) { throw error51; } throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error51 instanceof Error ? error51.message : String(error51)}`); } } return result; } } } /** * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` * notification for the specified elicitation ID. * * @param elicitationId The ID of the elicitation to mark as complete. * @param options Optional notification options. Useful when the completion notification should be related to a prior request. * @returns A function that emits the completion notification when awaited. */ createElicitationCompletionNotifier(elicitationId, options) { if (!this._clientCapabilities?.elicitation?.url) { throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)"); } return () => this.notification({ method: "notifications/elicitation/complete", params: { elicitationId } }, options); } async listRoots(params, options) { return this.request({ method: "roots/list", params }, ListRootsResultSchema, options); } /** * Sends a logging message to the client, if connected. * Note: You only need to send the parameters object, not the entire JSON RPC message * @see LoggingMessageNotification * @param params * @param sessionId optional for stateless and backward compatibility */ async sendLoggingMessage(params, sessionId) { if (this._capabilities.logging) { if (!this.isMessageIgnored(params.level, sessionId)) { return this.notification({ method: "notifications/message", params }); } } } async sendResourceUpdated(params) { return this.notification({ method: "notifications/resources/updated", params }); } async sendResourceListChanged() { return this.notification({ method: "notifications/resources/list_changed" }); } async sendToolListChanged() { return this.notification({ method: "notifications/tools/list_changed" }); } async sendPromptListChanged() { return this.notification({ method: "notifications/prompts/list_changed" }); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js init_define_KSQL_DOCS(); var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable"); function isCompletable(schema) { return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; } function getCompleter(schema) { const meta3 = schema[COMPLETABLE_SYMBOL]; return meta3?.complete; } var McpZodTypeKind; (function(McpZodTypeKind2) { McpZodTypeKind2["Completable"] = "McpCompletable"; })(McpZodTypeKind || (McpZodTypeKind = {})); // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js init_define_KSQL_DOCS(); var MAX_TEMPLATE_LENGTH = 1e6; var MAX_VARIABLE_LENGTH = 1e6; var MAX_TEMPLATE_EXPRESSIONS = 1e4; var MAX_REGEX_LENGTH = 1e6; var UriTemplate = class _UriTemplate { /** * Returns true if the given string contains any URI template expressions. * A template expression is a sequence of characters enclosed in curly braces, * like {foo} or {?bar}. */ static isTemplate(str) { return /\{[^}\s]+\}/.test(str); } static validateLength(str, max, context) { if (str.length > max) { throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); } } get variableNames() { return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); } constructor(template) { _UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); this.template = template; this.parts = this.parse(template); } toString() { return this.template; } parse(template) { const parts = []; let currentText = ""; let i = 0; let expressionCount = 0; while (i < template.length) { if (template[i] === "{") { if (currentText) { parts.push(currentText); currentText = ""; } const end = template.indexOf("}", i); if (end === -1) throw new Error("Unclosed template expression"); expressionCount++; if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); } const expr = template.slice(i + 1, end); const operator = this.getOperator(expr); const exploded = expr.includes("*"); const names = this.getNames(expr); const name = names[0]; for (const name2 of names) { _UriTemplate.validateLength(name2, MAX_VARIABLE_LENGTH, "Variable name"); } parts.push({ name, operator, names, exploded }); i = end + 1; } else { currentText += template[i]; i++; } } if (currentText) { parts.push(currentText); } return parts; } getOperator(expr) { const operators = ["+", "#", ".", "/", "?", "&"]; return operators.find((op) => expr.startsWith(op)) || ""; } getNames(expr) { const operator = this.getOperator(expr); return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); } encodeValue(value, operator) { _UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); if (operator === "+" || operator === "#") { return encodeURI(value); } return encodeURIComponent(value); } expandPart(part, variables) { if (part.operator === "?" || part.operator === "&") { const pairs = part.names.map((name) => { const value2 = variables[name]; if (value2 === void 0) return ""; const encoded2 = Array.isArray(value2) ? value2.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value2.toString(), part.operator); return `${name}=${encoded2}`; }).filter((pair) => pair.length > 0); if (pairs.length === 0) return ""; const separator = part.operator === "?" ? "?" : "&"; return separator + pairs.join("&"); } if (part.names.length > 1) { const values2 = part.names.map((name) => variables[name]).filter((v) => v !== void 0); if (values2.length === 0) return ""; return values2.map((v) => Array.isArray(v) ? v[0] : v).join(","); } const value = variables[part.name]; if (value === void 0) return ""; const values = Array.isArray(value) ? value : [value]; const encoded = values.map((v) => this.encodeValue(v, part.operator)); switch (part.operator) { case "": return encoded.join(","); case "+": return encoded.join(","); case "#": return "#" + encoded.join(","); case ".": return "." + encoded.join("."); case "/": return "/" + encoded.join("/"); default: return encoded.join(","); } } expand(variables) { let result = ""; let hasQueryParam = false; for (const part of this.parts) { if (typeof part === "string") { result += part; continue; } const expanded = this.expandPart(part, variables); if (!expanded) continue; if ((part.operator === "?" || part.operator === "&") && hasQueryParam) { result += expanded.replace("?", "&"); } else { result += expanded; } if (part.operator === "?" || part.operator === "&") { hasQueryParam = true; } } return result; } escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } partToRegExp(part) { const patterns = []; for (const name2 of part.names) { _UriTemplate.validateLength(name2, MAX_VARIABLE_LENGTH, "Variable name"); } if (part.operator === "?" || part.operator === "&") { for (let i = 0; i < part.names.length; i++) { const name2 = part.names[i]; const prefix = i === 0 ? "\\" + part.operator : "&"; patterns.push({ pattern: prefix + this.escapeRegExp(name2) + "=([^&]+)", name: name2 }); } return patterns; } let pattern; const name = part.name; switch (part.operator) { case "": pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; break; case "+": case "#": pattern = "(.+)"; break; case ".": pattern = "\\.([^/,]+)"; break; case "/": pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); break; default: pattern = "([^/]+)"; } patterns.push({ pattern, name }); return patterns; } match(uri) { _UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); let pattern = "^"; const names = []; for (const part of this.parts) { if (typeof part === "string") { pattern += this.escapeRegExp(part); } else { const patterns = this.partToRegExp(part); for (const { pattern: partPattern, name } of patterns) { pattern += partPattern; names.push({ name, exploded: part.exploded }); } } } pattern += "$"; _UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); const regex = new RegExp(pattern); const match = uri.match(regex); if (!match) return null; const result = {}; for (let i = 0; i < names.length; i++) { const { name, exploded } = names[i]; const value = match[i + 1]; const cleanName = name.replace("*", ""); if (exploded && value.includes(",")) { result[cleanName] = value.split(","); } else { result[cleanName] = value; } } return result; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js init_define_KSQL_DOCS(); var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; function validateToolName(name) { const warnings = []; if (name.length === 0) { return { isValid: false, warnings: ["Tool name cannot be empty"] }; } if (name.length > 128) { return { isValid: false, warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] }; } if (name.includes(" ")) { warnings.push("Tool name contains spaces, which may cause parsing issues"); } if (name.includes(",")) { warnings.push("Tool name contains commas, which may cause parsing issues"); } if (name.startsWith("-") || name.endsWith("-")) { warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); } if (name.startsWith(".") || name.endsWith(".")) { warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); } if (!TOOL_NAME_REGEX.test(name)) { const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); return { isValid: false, warnings }; } return { isValid: true, warnings }; } function issueToolNameWarning(name, warnings) { if (warnings.length > 0) { console.warn(`Tool name validation warning for "${name}":`); for (const warning of warnings) { console.warn(` - ${warning}`); } console.warn("Tool registration will proceed, but this may cause compatibility issues."); console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); } } function validateAndWarnToolName(name) { const result = validateToolName(name); issueToolNameWarning(name, result.warnings); return result.isValid; } // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js init_define_KSQL_DOCS(); var ExperimentalMcpServerTasks = class { constructor(_mcpServer) { this._mcpServer = _mcpServer; } registerToolTask(name, config2, handler) { const execution = { taskSupport: "required", ...config2.execution }; if (execution.taskSupport === "forbidden") { throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`); } const mcpServerInternal = this._mcpServer; return mcpServerInternal._createRegisteredTool(name, config2.title, config2.description, config2.inputSchema, config2.outputSchema, config2.annotations, execution, config2._meta, handler); } }; // node_modules/zod/index.js init_define_KSQL_DOCS(); // node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js var McpServer = class { constructor(serverInfo, options) { this._registeredResources = {}; this._registeredResourceTemplates = {}; this._registeredTools = {}; this._registeredPrompts = {}; this._toolHandlersInitialized = false; this._completionHandlerInitialized = false; this._resourceHandlersInitialized = false; this._promptHandlersInitialized = false; this.server = new Server(serverInfo, options); } /** * Access experimental features. * * WARNING: These APIs are experimental and may change without notice. * * @experimental */ get experimental() { if (!this._experimental) { this._experimental = { tasks: new ExperimentalMcpServerTasks(this) }; } return this._experimental; } /** * Attaches to the given transport, starts it, and starts listening for messages. * * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. */ async connect(transport) { return await this.server.connect(transport); } /** * Closes the connection. */ async close() { await this.server.close(); } setToolRequestHandlers() { if (this._toolHandlersInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); this.server.registerCapabilities({ tools: { listChanged: true } }); this.server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { const toolDefinition = { name, title: tool.title, description: tool.description, inputSchema: (() => { const obj = normalizeObjectSchema(tool.inputSchema); return obj ? toJsonSchemaCompat(obj, { strictUnions: true, pipeStrategy: "input" }) : EMPTY_OBJECT_JSON_SCHEMA; })(), annotations: tool.annotations, execution: tool.execution, _meta: tool._meta }; if (tool.outputSchema) { const obj = normalizeObjectSchema(tool.outputSchema); if (obj) { toolDefinition.outputSchema = toJsonSchemaCompat(obj, { strictUnions: true, pipeStrategy: "output" }); } } return toolDefinition; }) })); this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { try { const tool = this._registeredTools[request.params.name]; if (!tool) { throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); } if (!tool.enabled) { throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); } const isTaskRequest = !!request.params.task; const taskSupport = tool.execution?.taskSupport; const isTaskHandler = "createTask" in tool.handler; if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) { throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); } if (taskSupport === "required" && !isTaskRequest) { throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); } if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) { return await this.handleAutomaticTaskPolling(tool, request, extra); } const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); const result = await this.executeToolHandler(tool, args, extra); if (isTaskRequest) { return result; } await this.validateToolOutput(tool, result, request.params.name); return result; } catch (error51) { if (error51 instanceof McpError) { if (error51.code === ErrorCode.UrlElicitationRequired) { throw error51; } } return this.createToolError(error51 instanceof Error ? error51.message : String(error51)); } }); this._toolHandlersInitialized = true; } /** * Creates a tool error result. * * @param errorMessage - The error message. * @returns The tool error result. */ createToolError(errorMessage2) { return { content: [ { type: "text", text: errorMessage2 } ], isError: true }; } /** * Validates tool input arguments against the tool's input schema. */ async validateToolInput(tool, args, toolName) { if (!tool.inputSchema) { return void 0; } const inputObj = normalizeObjectSchema(tool.inputSchema); const schemaToParse = inputObj ?? tool.inputSchema; const parseResult = await safeParseAsync2(schemaToParse, args); if (!parseResult.success) { const error51 = "error" in parseResult ? parseResult.error : "Unknown error"; const errorMessage2 = getParseErrorMessage(error51); throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage2}`); } return parseResult.data; } /** * Validates tool output against the tool's output schema. */ async validateToolOutput(tool, result, toolName) { if (!tool.outputSchema) { return; } if (!("content" in result)) { return; } if (result.isError) { return; } if (!result.structuredContent) { throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); } const outputObj = normalizeObjectSchema(tool.outputSchema); const parseResult = await safeParseAsync2(outputObj, result.structuredContent); if (!parseResult.success) { const error51 = "error" in parseResult ? parseResult.error : "Unknown error"; const errorMessage2 = getParseErrorMessage(error51); throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage2}`); } } /** * Executes a tool handler (either regular or task-based). */ async executeToolHandler(tool, args, extra) { const handler = tool.handler; const isTaskHandler = "createTask" in handler; if (isTaskHandler) { if (!extra.taskStore) { throw new Error("No task store provided."); } const taskExtra = { ...extra, taskStore: extra.taskStore }; if (tool.inputSchema) { const typedHandler = handler; return await Promise.resolve(typedHandler.createTask(args, taskExtra)); } else { const typedHandler = handler; return await Promise.resolve(typedHandler.createTask(taskExtra)); } } if (tool.inputSchema) { const typedHandler = handler; return await Promise.resolve(typedHandler(args, extra)); } else { const typedHandler = handler; return await Promise.resolve(typedHandler(extra)); } } /** * Handles automatic task polling for tools with taskSupport 'optional'. */ async handleAutomaticTaskPolling(tool, request, extra) { if (!extra.taskStore) { throw new Error("No task store provided for task-capable tool."); } const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); const handler = tool.handler; const taskExtra = { ...extra, taskStore: extra.taskStore }; const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : ( // eslint-disable-next-line @typescript-eslint/no-explicit-any await Promise.resolve(handler.createTask(taskExtra)) ); const taskId = createTaskResult.task.taskId; let task = createTaskResult.task; const pollInterval = task.pollInterval ?? 5e3; while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") { await new Promise((resolve3) => setTimeout(resolve3, pollInterval)); const updatedTask = await extra.taskStore.getTask(taskId); if (!updatedTask) { throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`); } task = updatedTask; } return await extra.taskStore.getTaskResult(taskId); } setCompletionRequestHandler() { if (this._completionHandlerInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); this.server.registerCapabilities({ completions: {} }); this.server.setRequestHandler(CompleteRequestSchema, async (request) => { switch (request.params.ref.type) { case "ref/prompt": assertCompleteRequestPrompt(request); return this.handlePromptCompletion(request, request.params.ref); case "ref/resource": assertCompleteRequestResourceTemplate(request); return this.handleResourceCompletion(request, request.params.ref); default: throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); } }); this._completionHandlerInitialized = true; } async handlePromptCompletion(request, ref) { const prompt = this._registeredPrompts[ref.name]; if (!prompt) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); } if (!prompt.enabled) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); } if (!prompt.argsSchema) { return EMPTY_COMPLETION_RESULT; } const promptShape = getObjectShape(prompt.argsSchema); const field = promptShape?.[request.params.argument.name]; if (!isCompletable(field)) { return EMPTY_COMPLETION_RESULT; } const completer = getCompleter(field); if (!completer) { return EMPTY_COMPLETION_RESULT; } const suggestions = await completer(request.params.argument.value, request.params.context); return createCompletionResult(suggestions); } async handleResourceCompletion(request, ref) { const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); if (!template) { if (this._registeredResources[ref.uri]) { return EMPTY_COMPLETION_RESULT; } throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); } const completer = template.resourceTemplate.completeCallback(request.params.argument.name); if (!completer) { return EMPTY_COMPLETION_RESULT; } const suggestions = await completer(request.params.argument.value, request.params.context); return createCompletionResult(suggestions); } setResourceRequestHandlers() { if (this._resourceHandlersInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); this.server.registerCapabilities({ resources: { listChanged: true } }); this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ uri, name: resource.name, ...resource.metadata })); const templateResources = []; for (const template of Object.values(this._registeredResourceTemplates)) { if (!template.resourceTemplate.listCallback) { continue; } const result = await template.resourceTemplate.listCallback(extra); for (const resource of result.resources) { templateResources.push({ ...template.metadata, // the defined resource metadata should override the template metadata if present ...resource }); } } return { resources: [...resources, ...templateResources] }; }); this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ name, uriTemplate: template.resourceTemplate.uriTemplate.toString(), ...template.metadata })); return { resourceTemplates }; }); this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { const uri = new URL(request.params.uri); const resource = this._registeredResources[uri.toString()]; if (resource) { if (!resource.enabled) { throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); } return resource.readCallback(uri, extra); } for (const template of Object.values(this._registeredResourceTemplates)) { const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); if (variables) { return template.readCallback(uri, variables, extra); } } throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); }); this._resourceHandlersInitialized = true; } setPromptRequestHandlers() { if (this._promptHandlersInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); this.server.registerCapabilities({ prompts: { listChanged: true } }); this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { return { name, title: prompt.title, description: prompt.description, arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0 }; }) })); this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { const prompt = this._registeredPrompts[request.params.name]; if (!prompt) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); } if (!prompt.enabled) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); } if (prompt.argsSchema) { const argsObj = normalizeObjectSchema(prompt.argsSchema); const parseResult = await safeParseAsync2(argsObj, request.params.arguments); if (!parseResult.success) { const error51 = "error" in parseResult ? parseResult.error : "Unknown error"; const errorMessage2 = getParseErrorMessage(error51); throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage2}`); } const args = parseResult.data; const cb = prompt.callback; return await Promise.resolve(cb(args, extra)); } else { const cb = prompt.callback; return await Promise.resolve(cb(extra)); } }); this._promptHandlersInitialized = true; } resource(name, uriOrTemplate, ...rest) { let metadata; if (typeof rest[0] === "object") { metadata = rest.shift(); } const readCallback = rest[0]; if (typeof uriOrTemplate === "string") { if (this._registeredResources[uriOrTemplate]) { throw new Error(`Resource ${uriOrTemplate} is already registered`); } const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResource; } else { if (this._registeredResourceTemplates[name]) { throw new Error(`Resource template ${name} is already registered`); } const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResourceTemplate; } } registerResource(name, uriOrTemplate, config2, readCallback) { if (typeof uriOrTemplate === "string") { if (this._registeredResources[uriOrTemplate]) { throw new Error(`Resource ${uriOrTemplate} is already registered`); } const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, config2, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResource; } else { if (this._registeredResourceTemplates[name]) { throw new Error(`Resource template ${name} is already registered`); } const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, config2, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResourceTemplate; } } _createRegisteredResource(name, title, uri, metadata, readCallback) { const registeredResource = { name, title, metadata, readCallback, enabled: true, disable: () => registeredResource.update({ enabled: false }), enable: () => registeredResource.update({ enabled: true }), remove: () => registeredResource.update({ uri: null }), update: (updates) => { if (typeof updates.uri !== "undefined" && updates.uri !== uri) { delete this._registeredResources[uri]; if (updates.uri) this._registeredResources[updates.uri] = registeredResource; } if (typeof updates.name !== "undefined") registeredResource.name = updates.name; if (typeof updates.title !== "undefined") registeredResource.title = updates.title; if (typeof updates.metadata !== "undefined") registeredResource.metadata = updates.metadata; if (typeof updates.callback !== "undefined") registeredResource.readCallback = updates.callback; if (typeof updates.enabled !== "undefined") registeredResource.enabled = updates.enabled; this.sendResourceListChanged(); } }; this._registeredResources[uri] = registeredResource; return registeredResource; } _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { const registeredResourceTemplate = { resourceTemplate: template, title, metadata, readCallback, enabled: true, disable: () => registeredResourceTemplate.update({ enabled: false }), enable: () => registeredResourceTemplate.update({ enabled: true }), remove: () => registeredResourceTemplate.update({ name: null }), update: (updates) => { if (typeof updates.name !== "undefined" && updates.name !== name) { delete this._registeredResourceTemplates[name]; if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; } if (typeof updates.title !== "undefined") registeredResourceTemplate.title = updates.title; if (typeof updates.template !== "undefined") registeredResourceTemplate.resourceTemplate = updates.template; if (typeof updates.metadata !== "undefined") registeredResourceTemplate.metadata = updates.metadata; if (typeof updates.callback !== "undefined") registeredResourceTemplate.readCallback = updates.callback; if (typeof updates.enabled !== "undefined") registeredResourceTemplate.enabled = updates.enabled; this.sendResourceListChanged(); } }; this._registeredResourceTemplates[name] = registeredResourceTemplate; const variableNames = template.uriTemplate.variableNames; const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v)); if (hasCompleter) { this.setCompletionRequestHandler(); } return registeredResourceTemplate; } _createRegisteredPrompt(name, title, description, argsSchema, callback) { const registeredPrompt = { title, description, argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema), callback, enabled: true, disable: () => registeredPrompt.update({ enabled: false }), enable: () => registeredPrompt.update({ enabled: true }), remove: () => registeredPrompt.update({ name: null }), update: (updates) => { if (typeof updates.name !== "undefined" && updates.name !== name) { delete this._registeredPrompts[name]; if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; } if (typeof updates.title !== "undefined") registeredPrompt.title = updates.title; if (typeof updates.description !== "undefined") registeredPrompt.description = updates.description; if (typeof updates.argsSchema !== "undefined") registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); if (typeof updates.callback !== "undefined") registeredPrompt.callback = updates.callback; if (typeof updates.enabled !== "undefined") registeredPrompt.enabled = updates.enabled; this.sendPromptListChanged(); } }; this._registeredPrompts[name] = registeredPrompt; if (argsSchema) { const hasCompletable = Object.values(argsSchema).some((field) => { const inner = field instanceof ZodOptional2 ? field._def?.innerType : field; return isCompletable(inner); }); if (hasCompletable) { this.setCompletionRequestHandler(); } } return registeredPrompt; } _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { validateAndWarnToolName(name); const registeredTool = { title, description, inputSchema: getZodSchemaObject(inputSchema), outputSchema: getZodSchemaObject(outputSchema), annotations, execution, _meta, handler, enabled: true, disable: () => registeredTool.update({ enabled: false }), enable: () => registeredTool.update({ enabled: true }), remove: () => registeredTool.update({ name: null }), update: (updates) => { if (typeof updates.name !== "undefined" && updates.name !== name) { if (typeof updates.name === "string") { validateAndWarnToolName(updates.name); } delete this._registeredTools[name]; if (updates.name) this._registeredTools[updates.name] = registeredTool; } if (typeof updates.title !== "undefined") registeredTool.title = updates.title; if (typeof updates.description !== "undefined") registeredTool.description = updates.description; if (typeof updates.paramsSchema !== "undefined") registeredTool.inputSchema = objectFromShape(updates.paramsSchema); if (typeof updates.outputSchema !== "undefined") registeredTool.outputSchema = objectFromShape(updates.outputSchema); if (typeof updates.callback !== "undefined") registeredTool.handler = updates.callback; if (typeof updates.annotations !== "undefined") registeredTool.annotations = updates.annotations; if (typeof updates._meta !== "undefined") registeredTool._meta = updates._meta; if (typeof updates.enabled !== "undefined") registeredTool.enabled = updates.enabled; this.sendToolListChanged(); } }; this._registeredTools[name] = registeredTool; this.setToolRequestHandlers(); this.sendToolListChanged(); return registeredTool; } /** * tool() implementation. Parses arguments passed to overrides defined above. */ tool(name, ...rest) { if (this._registeredTools[name]) { throw new Error(`Tool ${name} is already registered`); } let description; let inputSchema; let outputSchema; let annotations; if (typeof rest[0] === "string") { description = rest.shift(); } if (rest.length > 1) { const firstArg = rest[0]; if (isZodRawShapeCompat(firstArg)) { inputSchema = rest.shift(); if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { annotations = rest.shift(); } } else if (typeof firstArg === "object" && firstArg !== null) { if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) { throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`); } annotations = rest.shift(); } } const callback = rest[0]; return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback); } /** * Registers a tool with a config object and callback. */ registerTool(name, config2, cb) { if (this._registeredTools[name]) { throw new Error(`Tool ${name} is already registered`); } const { title, description, inputSchema, outputSchema, annotations, _meta } = config2; return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb); } prompt(name, ...rest) { if (this._registeredPrompts[name]) { throw new Error(`Prompt ${name} is already registered`); } let description; if (typeof rest[0] === "string") { description = rest.shift(); } let argsSchema; if (rest.length > 1) { argsSchema = rest.shift(); } const cb = rest[0]; const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb); this.setPromptRequestHandlers(); this.sendPromptListChanged(); return registeredPrompt; } /** * Registers a prompt with a config object and callback. */ registerPrompt(name, config2, cb) { if (this._registeredPrompts[name]) { throw new Error(`Prompt ${name} is already registered`); } const { title, description, argsSchema } = config2; const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); this.setPromptRequestHandlers(); this.sendPromptListChanged(); return registeredPrompt; } /** * Checks if the server is connected to a transport. * @returns True if the server is connected */ isConnected() { return this.server.transport !== void 0; } /** * Sends a logging message to the client, if connected. * Note: You only need to send the parameters object, not the entire JSON RPC message * @see LoggingMessageNotification * @param params * @param sessionId optional for stateless and backward compatibility */ async sendLoggingMessage(params, sessionId) { return this.server.sendLoggingMessage(params, sessionId); } /** * Sends a resource list changed event to the client, if connected. */ sendResourceListChanged() { if (this.isConnected()) { this.server.sendResourceListChanged(); } } /** * Sends a tool list changed event to the client, if connected. */ sendToolListChanged() { if (this.isConnected()) { this.server.sendToolListChanged(); } } /** * Sends a prompt list changed event to the client, if connected. */ sendPromptListChanged() { if (this.isConnected()) { this.server.sendPromptListChanged(); } } }; var ResourceTemplate = class { constructor(uriTemplate, _callbacks) { this._callbacks = _callbacks; this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; } /** * Gets the URI template pattern. */ get uriTemplate() { return this._uriTemplate; } /** * Gets the list callback, if one was provided. */ get listCallback() { return this._callbacks.list; } /** * Gets the callback for completing a specific URI template variable, if one was provided. */ completeCallback(variable) { return this._callbacks.complete?.[variable]; } }; var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} }; function isZodTypeLike(value) { return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function"; } function isZodSchemaInstance(obj) { return "_def" in obj || "_zod" in obj || isZodTypeLike(obj); } function isZodRawShapeCompat(obj) { if (typeof obj !== "object" || obj === null) { return false; } if (isZodSchemaInstance(obj)) { return false; } if (Object.keys(obj).length === 0) { return true; } return Object.values(obj).some(isZodTypeLike); } function getZodSchemaObject(schema) { if (!schema) { return void 0; } if (isZodRawShapeCompat(schema)) { return objectFromShape(schema); } if (!isZodSchemaInstance(schema)) { throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object"); } return schema; } function promptArgumentsFromSchema(schema) { const shape = getObjectShape(schema); if (!shape) return []; return Object.entries(shape).map(([name, field]) => { const description = getSchemaDescription(field); const isOptional = isSchemaOptional(field); return { name, description, required: !isOptional }; }); } function getMethodValue(schema) { const shape = getObjectShape(schema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error("Schema is missing a method literal"); } const value = getLiteralValue(methodSchema); if (typeof value === "string") { return value; } throw new Error("Schema method literal must be a string"); } function createCompletionResult(suggestions) { return { completion: { values: suggestions.slice(0, 100), total: suggestions.length, hasMore: suggestions.length > 100 } }; } var EMPTY_COMPLETION_RESULT = { completion: { values: [], hasMore: false } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js init_define_KSQL_DOCS(); var import_node_process = __toESM(require("node:process"), 1); // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js init_define_KSQL_DOCS(); var ReadBuffer = class { append(chunk3) { this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk3]) : chunk3; } readMessage() { if (!this._buffer) { return null; } const index = this._buffer.indexOf("\n"); if (index === -1) { return null; } const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); this._buffer = this._buffer.subarray(index + 1); return deserializeMessage(line); } clear() { this._buffer = void 0; } }; function deserializeMessage(line) { return JSONRPCMessageSchema.parse(JSON.parse(line)); } function serializeMessage(message) { return JSON.stringify(message) + "\n"; } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js var StdioServerTransport = class { constructor(_stdin = import_node_process.default.stdin, _stdout = import_node_process.default.stdout) { this._stdin = _stdin; this._stdout = _stdout; this._readBuffer = new ReadBuffer(); this._started = false; this._ondata = (chunk3) => { this._readBuffer.append(chunk3); this.processReadBuffer(); }; this._onerror = (error51) => { this.onerror?.(error51); }; } /** * Starts listening for messages on stdin. */ async start() { if (this._started) { throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); } this._started = true; this._stdin.on("data", this._ondata); this._stdin.on("error", this._onerror); } processReadBuffer() { while (true) { try { const message = this._readBuffer.readMessage(); if (message === null) { break; } this.onmessage?.(message); } catch (error51) { this.onerror?.(error51); } } } async close() { this._stdin.off("data", this._ondata); this._stdin.off("error", this._onerror); const remainingDataListeners = this._stdin.listenerCount("data"); if (remainingDataListeners === 0) { this._stdin.pause(); } this._readBuffer.clear(); this.onclose?.(); } send(message) { return new Promise((resolve3) => { const json2 = serializeMessage(message); if (this._stdout.write(json2)) { resolve3(); } else { this._stdout.once("drain", resolve3); } }); } }; // src/mcp/docsResources.ts init_define_KSQL_DOCS(); var import_node_fs = require("node:fs"); var import_node_path = require("node:path"); var import_docsResourceBuilder = __toESM(require_docsResourceBuilder()); function loadFromRepoDocs() { const docsDir = (0, import_node_path.resolve)(__dirname, "../../docs"); return (0, import_docsResourceBuilder.buildDocsResourceMap)( (0, import_node_fs.readFileSync)((0, import_node_path.resolve)(docsDir, "ksql_language_reference.md"), "utf8"), (0, import_node_fs.readFileSync)((0, import_node_path.resolve)(docsDir, "ksql_batch_recipes.md"), "utf8") ); } function freezeEmbeddedMap(map2) { for (const collection of [map2.languageReference, map2.recipes]) { for (const section of Object.values(collection.sections)) Object.freeze(section); Object.freeze(collection.sections); Object.freeze(collection); } return Object.freeze(map2); } var KSQL_DOCS = typeof define_KSQL_DOCS_default !== "undefined" ? freezeEmbeddedMap(define_KSQL_DOCS_default) : loadFromRepoDocs(); var LANGUAGE_SECTION_KEYS = Object.freeze(Object.keys(KSQL_DOCS.languageReference.sections)); var RECIPE_KEYS = Object.freeze(Object.keys(KSQL_DOCS.recipes.sections)); function frozenList(values) { return Object.freeze(values); } var KSQL_FUNCTION_CATALOG = Object.freeze({ scalar: frozenList([ "UPPER", "LOWER", "TRIM", "LTRIM", "RTRIM", "LENGTH", "LENGTH_CHAR", "SUBSTRING", "LEFT", "RIGHT", "INSTR", "CONCAT", "REPLACE", "REGEXP_LIKE", "REGEXP_REPLACE", "REGEXP_SUBSTR", "TRANSLATE", "COALESCE", "ISNULL", "NULLIF", "GREATEST", "LEAST", "LPAD", "RPAD", "ROUND", "FLOOR", "CEIL", "TRUNCATE", "ABS", "MOD", "POWER", "SQRT", "FORMAT", "CAST", "YEAR", "MONTH", "DAY", "DAYOFWEEK", "QUARTER", "WEEK", "DATE_FORMAT", "DATEDIFF", "DATE_ADD", "LAST_DAY", "CURRENT_DATE", "CURRENT_TIMESTAMP" ]), aggregate: frozenList([ "COUNT", "SUM", "AVG", "MIN", "MAX", "GROUP_CONCAT", "STDDEV_POP", "STDDEV_SAMP", "VAR_POP", "VAR_SAMP", "MEDIAN", "MODE" ]), window: frozenList(["ROW_NUMBER", "RANK", "DENSE_RANK"]), contextual: frozenList(["TODAY", "NOW", "LOGINUSER"]), aliases: frozenList([ "SUBSTR\u2192SUBSTRING", "CONVERT\u2192CAST", "CEILING\u2192CEIL", "TRUNC\u2192TRUNCATE", "POW\u2192POWER" ]), syntax: frozenList([ "IF(cond, then, else)", "||", "LIKE", "KLIKE", "IN", "BETWEEN", "IS NULL", "CASE WHEN" ]) }); var KSQL_DOCS_SECTION_KEYS = Object.freeze([ "language-reference", ...LANGUAGE_SECTION_KEYS.map((key) => `language-reference/${key}`), "recipes", ...RECIPE_KEYS.map((key) => `recipes/${key}`) ]); function buildKsqlDocsIndex() { return [ KSQL_DOCS.languageReference.index.trimEnd(), 'Tool fallback example: ksql_docs {"section":"language-reference/05-string-number-functions"}', KSQL_DOCS.recipes.index.trimEnd(), 'Tool fallback example: ksql_docs {"section":"recipes/r1"}', "## ksql_docs section keys", ...KSQL_DOCS_SECTION_KEYS.map((key) => `- ${key}`) ].join("\n\n"); } var KSQL_DOCS_INDEX = buildKsqlDocsIndex(); var VALID_KEY_HINT = "Valid keys: language-reference, language-reference/, recipes, recipes/r1..r12. Call ksql_docs without arguments for the full key list."; function resolveKsqlDocsSection(section) { if (section === void 0) return KSQL_DOCS_INDEX; const key = section.trim().replace(/^ksql:\/\//, ""); if (key === "language-reference") return KSQL_DOCS.languageReference.index; if (key === "recipes") return KSQL_DOCS.recipes.index; if (key.startsWith("language-reference/")) { const text = KSQL_DOCS.languageReference.sections[key.slice("language-reference/".length)]?.text; if (text !== void 0) return text; } if (key.startsWith("recipes/")) { const text = KSQL_DOCS.recipes.sections[key.slice("recipes/".length)]?.text; if (text !== void 0) return text; } throw new Error(`ArgumentError: Unknown ksql_docs section key: ${key}. ${VALID_KEY_HINT}`); } // src/mcp/tools.ts init_define_KSQL_DOCS(); // src/core/index.ts init_define_KSQL_DOCS(); // src/execute.ts init_define_KSQL_DOCS(); // src/lexer/lexer.ts init_define_KSQL_DOCS(); // src/lexer/tokens.ts init_define_KSQL_DOCS(); var KEYWORDS = /* @__PURE__ */ new Map([ ["UNION", "UNION" /* UNION */], ["ALL", "ALL" /* ALL */], ["WITH", "WITH" /* WITH */], ["SHOW", "SHOW" /* SHOW */], ["DESCRIBE", "DESCRIBE" /* DESCRIBE */], ["APPS", "APPS" /* APPS */], ["EXPLAIN", "EXPLAIN" /* EXPLAIN */], ["UPSERT", "UPSERT" /* UPSERT */], ["REORDER", "REORDER" /* REORDER */], ["DUPLICATE", "DUPLICATE" /* DUPLICATE */], ["SELECT", "SELECT" /* SELECT */], ["DISTINCT", "DISTINCT" /* DISTINCT */], ["FROM", "FROM" /* FROM */], ["AS", "AS" /* AS */], ["WHERE", "WHERE" /* WHERE */], ["INSERT", "INSERT" /* INSERT */], ["INTO", "INTO" /* INTO */], ["VALUES", "VALUES" /* VALUES */], ["UPDATE", "UPDATE" /* UPDATE */], ["SET", "SET" /* SET */], ["DELETE", "DELETE" /* DELETE */], ["INNER", "INNER" /* INNER */], ["LEFT", "LEFT" /* LEFT */], ["RIGHT", "RIGHT" /* RIGHT */], ["JOIN", "JOIN" /* JOIN */], ["ON", "ON" /* ON */], ["GROUP", "GROUP" /* GROUP */], ["BY", "BY" /* BY */], ["HAVING", "HAVING" /* HAVING */], ["ORDER", "ORDER" /* ORDER */], ["KORDER", "KORDER" /* KORDER */], ["ASC", "ASC" /* ASC */], ["DESC", "DESC" /* DESC */], ["LIMIT", "LIMIT" /* LIMIT */], ["OFFSET", "OFFSET" /* OFFSET */], ["COUNT", "COUNT" /* COUNT */], ["SUM", "SUM" /* SUM */], ["AVG", "AVG" /* AVG */], ["MAX", "MAX" /* MAX */], ["MIN", "MIN" /* MIN */], ["GROUP_CONCAT", "GROUP_CONCAT" /* GROUP_CONCAT */], ["STDDEV_POP", "STDDEV_POP" /* STDDEV_POP */], ["STDDEV_SAMP", "STDDEV_SAMP" /* STDDEV_SAMP */], ["VAR_POP", "VAR_POP" /* VAR_POP */], ["VAR_SAMP", "VAR_SAMP" /* VAR_SAMP */], ["MEDIAN", "MEDIAN" /* MEDIAN */], ["MODE", "MODE" /* MODE */], ["ROW_NUMBER", "ROW_NUMBER" /* ROW_NUMBER */], ["RANK", "RANK" /* RANK */], ["DENSE_RANK", "DENSE_RANK" /* DENSE_RANK */], ["ASSERT", "ASSERT" /* ASSERT */], ["AND", "AND" /* AND */], ["OR", "OR" /* OR */], ["NOT", "NOT" /* NOT */], ["EXISTS", "EXISTS" /* EXISTS */], ["IS", "IS" /* IS */], ["NULL", "NULL" /* NULL */], ["LIKE", "LIKE" /* LIKE */], ["KLIKE", "KLIKE" /* KLIKE */], ["IN", "IN" /* IN */], ["BETWEEN", "BETWEEN" /* BETWEEN */], ["TODAY", "TODAY" /* TODAY */], ["NOW", "NOW" /* NOW */], ["LOGINUSER", "LOGINUSER" /* LOGINUSER */], ["CASE", "CASE" /* CASE */], ["WHEN", "WHEN" /* WHEN */], ["THEN", "THEN" /* THEN */], ["ELSE", "ELSE" /* ELSE */], ["END", "END" /* END */], ["UPPER", "UPPER" /* UPPER */], ["LOWER", "LOWER" /* LOWER */], ["TRIM", "TRIM" /* TRIM */], ["LTRIM", "LTRIM" /* LTRIM */], ["RTRIM", "RTRIM" /* RTRIM */], ["LENGTH", "LENGTH" /* LENGTH */], ["LENGTH_CHAR", "LENGTH_CHAR" /* LENGTH_CHAR */], ["SUBSTRING", "SUBSTRING" /* SUBSTRING */], ["SUBSTR", "SUBSTR" /* SUBSTR */], ["CONCAT", "CONCAT" /* CONCAT */], ["REPLACE", "REPLACE" /* REPLACE */], ["REGEXP_LIKE", "REGEXP_LIKE" /* REGEXP_LIKE */], ["REGEXP_REPLACE", "REGEXP_REPLACE" /* REGEXP_REPLACE */], ["REGEXP_SUBSTR", "REGEXP_SUBSTR" /* REGEXP_SUBSTR */], ["COALESCE", "COALESCE" /* COALESCE */], ["NULLIF", "NULLIF" /* NULLIF */], ["ISNULL", "ISNULL" /* ISNULL */], ["INSTR", "INSTR" /* INSTR */], ["GREATEST", "GREATEST" /* GREATEST */], ["LEAST", "LEAST" /* LEAST */], ["LPAD", "LPAD" /* LPAD */], ["RPAD", "RPAD" /* RPAD */], ["TRANSLATE", "TRANSLATE" /* TRANSLATE */], ["CAST", "CAST" /* CAST */], ["CONVERT", "CONVERT" /* CONVERT */], ["FORMAT", "FORMAT" /* FORMAT */], ["ROUND", "ROUND" /* ROUND */], ["FLOOR", "FLOOR" /* FLOOR */], ["CEIL", "CEIL" /* CEIL */], ["CEILING", "CEILING" /* CEILING */], ["TRUNCATE", "TRUNCATE" /* TRUNCATE */], ["TRUNC", "TRUNC" /* TRUNC */], ["ABS", "ABS" /* ABS */], ["MOD", "MOD" /* MOD */], ["POWER", "POWER" /* POWER */], ["POW", "POW" /* POW */], ["SQRT", "SQRT" /* SQRT */], ["YEAR", "YEAR" /* YEAR */], ["MONTH", "MONTH" /* MONTH */], ["DAY", "DAY" /* DAY */], ["DAYOFWEEK", "DAYOFWEEK" /* DAYOFWEEK */], ["QUARTER", "QUARTER" /* QUARTER */], ["WEEK", "WEEK" /* WEEK */], ["DATE_FORMAT", "DATE_FORMAT" /* DATE_FORMAT */], ["DATEDIFF", "DATEDIFF" /* DATEDIFF */], ["DATE_ADD", "DATE_ADD" /* DATE_ADD */], ["LAST_DAY", "LAST_DAY" /* LAST_DAY */], ["IF", "IF" /* IF */] ]); // src/lexer/lexer.ts var LexError = class extends Error { constructor(message, pos, input, unterminated = false) { const around = input.slice(Math.max(0, pos - 10), pos + 10); super(`${message}\uFF08\u4F4D\u7F6E ${pos}\u3001\u524D\u5F8C: \u300C${around}\u300D\uFF09`); this.pos = pos; this.input = input; this.unterminated = unterminated; this.name = "LexError"; } }; var Lexer = class { constructor(input) { this.input = input; this.pos = 0; } // ---------------------------------------------------------- // 公開 API: 全トークンを返す // ---------------------------------------------------------- tokenize() { const tokens = []; while (true) { const tok = this.nextToken(); tokens.push(tok); if (tok.kind === "EOF" /* EOF */) break; } return tokens; } // ---------------------------------------------------------- // 次のトークンを読み取る // ---------------------------------------------------------- nextToken() { this.skipWhitespaceAndComments(); if (this.pos >= this.input.length) { return this.makeToken("EOF" /* EOF */, "", this.pos); } const start = this.pos; const ch = this.input[this.pos]; if (ch === "'") return this.readString(start); if (ch === "`") return this.readBacktickIdent(start); if (isDigit(ch)) return this.readNumber(start); const opTok = this.tryReadOperator(start); if (opTok) return opTok; if (isIdentStart(ch)) return this.readIdentOrKeyword(start); if (ch === "#") return this.readHashIdent(start); if (ch === "@") return this.readVariable(start); throw new LexError( `\u4E88\u671F\u3057\u306A\u3044\u6587\u5B57 \u300C${ch}\u300D \u3067\u3059`, this.pos, this.input ); } // ---------------------------------------------------------- // 文字列リテラル: 'value' // シングルクォート内の '' はエスケープとして扱う // ---------------------------------------------------------- readString(start) { this.pos++; let value = ""; while (this.pos < this.input.length) { const ch = this.input[this.pos]; if (ch === "'") { this.pos++; if (this.pos < this.input.length && this.input[this.pos] === "'") { value += "'"; this.pos++; } else { return this.makeToken("STRING" /* STRING */, value, start); } } else { value += ch; this.pos++; } } throw new LexError("\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u304C\u9589\u3058\u3089\u308C\u3066\u3044\u307E\u305B\u3093", start, this.input, true); } // ---------------------------------------------------------- // バッククォート識別子: `field name` // ---------------------------------------------------------- readBacktickIdent(start) { this.pos++; let value = ""; while (this.pos < this.input.length) { const ch = this.input[this.pos]; if (ch === "`") { this.pos++; return this.makeToken("BIDENT" /* BIDENT */, value, start); } value += ch; this.pos++; } throw new LexError( "\u30D0\u30C3\u30AF\u30AF\u30A9\u30FC\u30C8\u8B58\u5225\u5B50\u304C\u9589\u3058\u3089\u308C\u3066\u3044\u307E\u305B\u3093", start, this.input, true ); } // ---------------------------------------------------------- // 数値: digits[.digits][e[+-]digits](先頭/末尾 dot は受理しない) // ---------------------------------------------------------- readNumber(start) { while (this.pos < this.input.length && isDigit(this.input[this.pos])) { this.pos++; } if (this.pos < this.input.length && this.input[this.pos] === "." && this.pos + 1 < this.input.length && isDigit(this.input[this.pos + 1])) { this.pos++; while (this.pos < this.input.length && isDigit(this.input[this.pos])) { this.pos++; } } if (this.pos < this.input.length && (this.input[this.pos] === "e" || this.input[this.pos] === "E")) { this.pos++; if (this.pos < this.input.length && (this.input[this.pos] === "+" || this.input[this.pos] === "-")) { this.pos++; } if (this.pos >= this.input.length || !isDigit(this.input[this.pos])) { throw new LexError("\u6307\u6570\u90E8\u306B\u306F\u6570\u5B57\u304C\u5FC5\u8981\u3067\u3059", start, this.input, this.pos >= this.input.length); } while (this.pos < this.input.length && isDigit(this.input[this.pos])) this.pos++; } return this.makeToken( "NUMBER" /* NUMBER */, this.input.slice(start, this.pos), start ); } // ---------------------------------------------------------- // 演算子・記号 // ---------------------------------------------------------- tryReadOperator(start) { const ch = this.input[this.pos]; const ch2 = this.input[this.pos + 1] ?? ""; if (ch === "!" && ch2 === "=") { this.pos += 2; return this.makeToken("!=" /* NEQ */, "!=", start); } if (ch === "<" && ch2 === ">") { this.pos += 2; return this.makeToken("<>" /* LT_GT */, "<>", start); } if (ch === ">" && ch2 === "=") { this.pos += 2; return this.makeToken(">=" /* GTE */, ">=", start); } if (ch === "<" && ch2 === "=") { this.pos += 2; return this.makeToken("<=" /* LTE */, "<=", start); } if (ch === "|" && ch2 === "|") { this.pos += 2; return this.makeToken("||" /* CONCAT_OP */, "||", start); } switch (ch) { case "=": this.pos++; return this.makeToken("=" /* EQ */, "=", start); case ">": this.pos++; return this.makeToken(">" /* GT */, ">", start); case "<": this.pos++; return this.makeToken("<" /* LT */, "<", start); case "*": this.pos++; return this.makeToken("*" /* STAR */, "*", start); case "+": this.pos++; return this.makeToken("+" /* PLUS */, "+", start); case "-": this.pos++; return this.makeToken("-" /* MINUS */, "-", start); case "/": this.pos++; return this.makeToken("/" /* SLASH */, "/", start); case "%": this.pos++; return this.makeToken("%" /* PERCENT */, "%", start); case "(": this.pos++; return this.makeToken("(" /* LPAREN */, "(", start); case ")": this.pos++; return this.makeToken(")" /* RPAREN */, ")", start); case "[": this.pos++; return this.makeToken("[" /* LBRACKET */, "[", start); case "]": this.pos++; return this.makeToken("]" /* RBRACKET */, "]", start); case ",": this.pos++; return this.makeToken("," /* COMMA */, ",", start); case ".": this.pos++; return this.makeToken("." /* DOT */, ".", start); case ";": this.pos++; return this.makeToken(";" /* SEMICOLON */, ";", start); } return null; } // ---------------------------------------------------------- // 識別子 / キーワード // ---------------------------------------------------------- readIdentOrKeyword(start) { while (this.pos < this.input.length && isIdentContinue(this.input[this.pos])) { this.pos++; } const raw = this.input.slice(start, this.pos); const upper = raw.toUpperCase(); const kind = KEYWORDS.get(upper) ?? "IDENT" /* IDENT */; const value = kind === "IDENT" /* IDENT */ ? raw : upper; return this.makeToken(kind, value, start); } // ---------------------------------------------------------- // 一時テーブル識別子: #temp // # は先頭のみ有効。isIdentStart に # を加えると isIdentContinue 経由で // 識別子の途中(APP#x 等)にも許容されてしまうため、専用分岐で読む。 // ---------------------------------------------------------- readHashIdent(start) { this.pos++; const next = this.input[this.pos] ?? ""; if (!isIdentStart(next)) { throw new LexError("\u300C#\u300D \u306E\u76F4\u5F8C\u306B\u306F\u8B58\u5225\u5B50\u304C\u5FC5\u8981\u3067\u3059", start, this.input); } while (this.pos < this.input.length && isIdentContinue(this.input[this.pos])) { this.pos++; } const value = this.input.slice(start, this.pos); if (this.input[this.pos] === "@") { throw new LexError( `@profile is not allowed on temp table ${value}.`, this.pos, this.input ); } return this.makeToken("IDENT" /* IDENT */, value, start); } /** バッチ変数: @[A-Za-z_][A-Za-z0-9_]{0,63} */ readVariable(start) { this.pos++; const first = this.input[this.pos] ?? ""; if (!/[A-Za-z_]/.test(first)) { throw new LexError("\u300C@\u300D \u306E\u76F4\u5F8C\u306B\u306F\u82F1\u5B57\u307E\u305F\u306F _ \u3067\u59CB\u307E\u308B\u5909\u6570\u540D\u304C\u5FC5\u8981\u3067\u3059", start, this.input); } this.pos++; while (this.pos < this.input.length && /[A-Za-z0-9_]/.test(this.input[this.pos])) { this.pos++; } const nameLength = this.pos - start - 1; if (nameLength > 64) { throw new LexError("\u5909\u6570\u540D\u306F 64 \u6587\u5B57\u4EE5\u5185\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", start, this.input); } return this.makeToken("VARIABLE" /* VARIABLE */, this.input.slice(start, this.pos), start); } // ---------------------------------------------------------- // 空白・コメントをスキップ // ---------------------------------------------------------- skipWhitespaceAndComments() { while (this.pos < this.input.length) { const ch = this.input[this.pos]; if (ch === " " || ch === " " || ch === "\r" || ch === "\n") { this.pos++; continue; } if (ch === "-" && this.input[this.pos + 1] === "-") { while (this.pos < this.input.length && this.input[this.pos] !== "\n") { this.pos++; } continue; } if (ch === "/" && this.input[this.pos + 1] === "*") { const commentStart = this.pos; this.pos += 2; let closed = false; while (this.pos < this.input.length) { if (this.input[this.pos] === "*" && this.input[this.pos + 1] === "/") { this.pos += 2; closed = true; break; } this.pos++; } if (!closed) { throw new LexError( "\u30D6\u30ED\u30C3\u30AF\u30B3\u30E1\u30F3\u30C8\u304C\u9589\u3058\u3089\u308C\u3066\u3044\u307E\u305B\u3093", commentStart, this.input, true ); } continue; } break; } } // ---------------------------------------------------------- // ヘルパー // ---------------------------------------------------------- makeToken(kind, value, pos) { return { kind, value, pos }; } }; function isIdentStart(ch) { const cp = ch.codePointAt(0); return cp >= 65 && cp <= 90 || // A-Z cp >= 97 && cp <= 122 || // a-z cp === 95 || // _ cp === 36 || // $ isJapanese(cp); } function isIdentContinue(ch) { const cp = ch.codePointAt(0); return isIdentStart(ch) || cp >= 48 && cp <= 57; } function isDigit(ch) { const cp = ch.codePointAt(0); return cp >= 48 && cp <= 57; } function isJapanese(cp) { return cp >= 12352 && cp <= 12543 || cp >= 13312 && cp <= 40959 || cp >= 63744 && cp <= 64255 || cp >= 65281 && cp <= 65376; } // src/parser/parser.ts init_define_KSQL_DOCS(); // src/types/ast.ts init_define_KSQL_DOCS(); // src/core/exactDecimal.ts init_define_KSQL_DOCS(); var DECIMAL_PATTERN = /^([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:[eE]([+-]?)(\d+))?$/; function parseSafeExponent(sign, digits) { if (digits === void 0) return 0; let value = 0; for (const digit of digits) { value = value * 10 + (digit.charCodeAt(0) - 48); if (!Number.isSafeInteger(value)) return null; } return sign === "-" ? -value : value; } function parseExactDecimal(input) { const match = DECIMAL_PATTERN.exec(input.trim()); if (match === null) return null; const exponent = parseSafeExponent(match[5], match[6]); if (exponent === null) return null; const fraction = match[3] ?? match[4] ?? ""; let coefficient = `${match[2] ?? ""}${fraction}`.replace(/^0+/, ""); if (coefficient === "") return { sign: 0, coefficient: "0", scale: 0 }; let scale = fraction.length - exponent; if (!Number.isSafeInteger(scale)) return null; const trailingZeros = /0+$/.exec(coefficient)?.[0].length ?? 0; if (trailingZeros > 0) { coefficient = coefficient.slice(0, -trailingZeros); scale -= trailingZeros; if (!Number.isSafeInteger(scale)) return null; } if (!Number.isSafeInteger(coefficient.length - scale)) return null; const sign = match[1] === "-" ? -1 : 1; return { sign, coefficient, scale }; } function formatPlainDecimal(dec) { if (dec.sign === 0) return "0"; const digits = dec.coefficient; let magnitude; if (dec.scale <= 0) { magnitude = `${digits}${"0".repeat(-dec.scale)}`; } else if (digits.length > dec.scale) { const point = digits.length - dec.scale; magnitude = `${digits.slice(0, point)}.${digits.slice(point)}`; } else { magnitude = `0.${"0".repeat(dec.scale - digits.length)}${digits}`; } return dec.sign === -1 ? `-${magnitude}` : magnitude; } function toPlainDecimal(input) { const dec = parseExactDecimal(input); return dec === null ? null : formatPlainDecimal(dec); } function compareMagnitudes(left, right) { const leftPoint = left.coefficient.length - left.scale; const rightPoint = right.coefficient.length - right.scale; if (!Number.isSafeInteger(leftPoint) || !Number.isSafeInteger(rightPoint)) { throw new Error("ArgumentError: exact decimal scale is outside the supported range."); } if (leftPoint !== rightPoint) return leftPoint < rightPoint ? -1 : 1; const width = Math.max(left.coefficient.length, right.coefficient.length); for (let index = 0; index < width; index++) { const a = index < left.coefficient.length ? left.coefficient.charCodeAt(index) : 48; const b = index < right.coefficient.length ? right.coefficient.charCodeAt(index) : 48; if (a !== b) return a < b ? -1 : 1; } return 0; } function compareExactDecimal(left, right) { if (left.sign !== right.sign) return left.sign < right.sign ? -1 : 1; if (left.sign === 0) return 0; const magnitude = compareMagnitudes(left, right); return left.sign === -1 ? magnitude === 0 ? 0 : magnitude === -1 ? 1 : -1 : magnitude; } function compareDecimal(left, right) { const a = parseExactDecimal(left); const b = parseExactDecimal(right); if (a === null || b === null) { throw new Error("ArgumentError: compareDecimal requires finite decimal inputs."); } return compareExactDecimal(a, b); } // src/types/ast.ts var NO_FROM_CTE_NAME = "__NO_FROM__"; function makeNumberLiteral(raw) { return { type: "NUMBER", value: Number(raw), raw }; } function numberLiteralText(node) { const source = node.raw ?? String(node.value); return toPlainDecimal(source) ?? source; } // src/core/aggregateExpression.ts init_define_KSQL_DOCS(); function quote(value) { return `'${value.replace(/'/g, "''")}'`; } function arithLabel(node, topLevel = false) { if (node.type === "FIELD_REF") return node.field; if (node.type === "NUMBER") return numberLiteralText(node); if (node.type === "STRING_FUNC") return stringFuncLabel(node); const label = `${arithLabel(node.left)}${node.op}${arithLabel(node.right)}`; return topLevel ? label : `(${label})`; } function fieldValueLabel(value) { if (value.type === "FIELD") return value.tableAlias ? `${value.tableAlias}.${value.field}` : value.field; if (value.type === "FUNC_FIELD") return stringFuncLabel(value.expr); if (value.type === "ARITH_FIELD") return arithLabel(value.expr); return caseLabel(value.expr); } function sqlValueLabel(value) { switch (value.type) { case "STRING": return quote(value.value); case "NUMBER": return numberLiteralText(value); case "VARIABLE": return `@${value.name}`; case "VARIABLE_IN_LIST": return `@${value.name}`; case "KINTONE_FUNC": return `${value.name}()`; case "ARRAY": return `[${value.elements.map((entry) => quote(entry.value)).join(",")}]`; case "IN_LIST": return `(${value.values.map(sqlValueLabel).join(",")})`; case "ARITH_VALUE": return arithLabel(value.expr); case "CASE_VALUE": return caseLabel(value.expr); case "SUBQUERY_IN_LIST": return "(SUBQUERY)"; case "SCALAR_SUBQUERY": return "(SUBQUERY)"; } } function whereLabel(expr) { switch (expr.type) { case "BINARY": return `${fieldValueLabel(expr.left)} ${expr.op.replace("_", " ")} ${sqlValueLabel(expr.right)}`; case "NULL_CHECK": return `${fieldValueLabel(expr.field)} IS ${expr.not ? "NOT " : ""}NULL`; case "LOGICAL": return `(${whereLabel(expr.left)} ${expr.op} ${whereLabel(expr.right)})`; case "NOT": return `NOT (${whereLabel(expr.expr)})`; case "GROUP": return `(${whereLabel(expr.expr)})`; case "BOOLEAN": return expr.value ? "TRUE" : "FALSE"; case "EXISTS": return `${expr.not ? "NOT " : ""}EXISTS (SUBQUERY)`; } } function caseResultLabel(result) { if (result.type === "ARRAY") return `[${result.elements.map((entry) => quote(entry.value)).join(",")}]`; if (result.type === "FIELD_REF" || result.type === "ARITH") return arithLabel(result); return scalarValueLabel(result); } function caseLabel(expr) { const branches = expr.branches.map((branch) => `WHEN ${whereLabel(branch.condition)} THEN ${caseResultLabel(branch.result)}`).join(" "); const otherwise = expr.elseResult === null ? "" : ` ELSE ${caseResultLabel(expr.elseResult)}`; return `CASE ${branches}${otherwise} END`; } function stringFuncArgLabel(arg) { if (arg.type === "AGG_REF") return aggregateSyntheticName(arg.func, arg.distinct, arg.arg); if (arg.type === "AGG_ARITH") return aggregateOperandLabel(arg); return scalarValueLabel(arg); } function stringFuncLabel(expr) { return `${expr.func}(${expr.args.map(stringFuncArgLabel).join(",")})`; } function scalarValueLabel(expr) { switch (expr.type) { case "STRING": return quote(expr.value); case "NUMBER": return numberLiteralText(expr); case "VARIABLE": return `@${expr.name}`; case "FIELD": return expr.tableAlias ? `${expr.tableAlias}.${expr.field}` : expr.field; case "STRING_FUNC": return stringFuncLabel(expr); case "CASE_WHEN": return caseLabel(expr); case "SCALAR_ARITH": return `(${scalarValueLabel(expr.left)}${expr.op}${scalarValueLabel(expr.right)})`; case "CONCAT_OP": return `(${scalarValueLabel(expr.left)}||${scalarValueLabel(expr.right)})`; } } function aggregateArgLabel(arg) { if (arg.type === "WILDCARD") return "*"; if (arg.type === "FIELD_REF" || arg.type === "ARITH") return arithLabel(arg, true); return scalarValueLabel(arg); } function aggregateSyntheticName(func, distinct, arg) { const label = aggregateArgLabel(arg); return distinct ? `${func}(DISTINCT ${label})` : `${func}(${label})`; } function aggregateOperandLabel(node) { if (node.type === "NUMBER") return numberLiteralText(node); if (node.type === "AGG_REF") return aggregateSyntheticName(node.func, node.distinct, node.arg); return `${aggregateOperandLabel(node.left)}${node.op}${aggregateOperandLabel(node.right)}`; } // src/parser/parser.ts var MAX_BATCH_STATEMENTS = 20; var PARSER_SCALAR_FUNCTION_TOKEN_MAP = Object.freeze({ ["UPPER" /* UPPER */]: "UPPER", ["LOWER" /* LOWER */]: "LOWER", ["TRIM" /* TRIM */]: "TRIM", ["LTRIM" /* LTRIM */]: "LTRIM", ["RTRIM" /* RTRIM */]: "RTRIM", ["LENGTH" /* LENGTH */]: "LENGTH", ["LENGTH_CHAR" /* LENGTH_CHAR */]: "LENGTH_CHAR", ["SUBSTRING" /* SUBSTRING */]: "SUBSTRING", ["SUBSTR" /* SUBSTR */]: "SUBSTRING", ["LEFT" /* LEFT */]: "LEFT", ["RIGHT" /* RIGHT */]: "RIGHT", ["INSTR" /* INSTR */]: "INSTR", ["CONCAT" /* CONCAT */]: "CONCAT", ["REPLACE" /* REPLACE */]: "REPLACE", ["REGEXP_LIKE" /* REGEXP_LIKE */]: "REGEXP_LIKE", ["REGEXP_REPLACE" /* REGEXP_REPLACE */]: "REGEXP_REPLACE", ["REGEXP_SUBSTR" /* REGEXP_SUBSTR */]: "REGEXP_SUBSTR", ["TRANSLATE" /* TRANSLATE */]: "TRANSLATE", ["COALESCE" /* COALESCE */]: "COALESCE", ["ISNULL" /* ISNULL */]: "ISNULL", ["NULLIF" /* NULLIF */]: "NULLIF", ["GREATEST" /* GREATEST */]: "GREATEST", ["LEAST" /* LEAST */]: "LEAST", ["LPAD" /* LPAD */]: "LPAD", ["RPAD" /* RPAD */]: "RPAD", ["ROUND" /* ROUND */]: "ROUND", ["FLOOR" /* FLOOR */]: "FLOOR", ["CEIL" /* CEIL */]: "CEIL", ["CEILING" /* CEILING */]: "CEIL", ["TRUNCATE" /* TRUNCATE */]: "TRUNCATE", ["TRUNC" /* TRUNC */]: "TRUNCATE", ["ABS" /* ABS */]: "ABS", ["MOD" /* MOD */]: "MOD", ["POWER" /* POWER */]: "POWER", ["POW" /* POW */]: "POWER", ["SQRT" /* SQRT */]: "SQRT", ["FORMAT" /* FORMAT */]: "FORMAT", ["CAST" /* CAST */]: "CAST", ["CONVERT" /* CONVERT */]: "CAST", ["YEAR" /* YEAR */]: "YEAR", ["MONTH" /* MONTH */]: "MONTH", ["DAY" /* DAY */]: "DAY", ["DAYOFWEEK" /* DAYOFWEEK */]: "DAYOFWEEK", ["QUARTER" /* QUARTER */]: "QUARTER", ["WEEK" /* WEEK */]: "WEEK", ["DATE_FORMAT" /* DATE_FORMAT */]: "DATE_FORMAT", ["DATEDIFF" /* DATEDIFF */]: "DATEDIFF", ["DATE_ADD" /* DATE_ADD */]: "DATE_ADD", ["LAST_DAY" /* LAST_DAY */]: "LAST_DAY" }); var PARSER_IDENT_SCALAR_FUNCTIONS = Object.freeze([ "CURRENT_DATE", "CURRENT_TIMESTAMP" ]); var PARSER_AGGREGATE_FUNCTION_TOKEN_MAP = Object.freeze({ ["COUNT" /* COUNT */]: "COUNT", ["SUM" /* SUM */]: "SUM", ["AVG" /* AVG */]: "AVG", ["MAX" /* MAX */]: "MAX", ["MIN" /* MIN */]: "MIN", ["GROUP_CONCAT" /* GROUP_CONCAT */]: "GROUP_CONCAT", ["STDDEV_POP" /* STDDEV_POP */]: "STDDEV_POP", ["STDDEV_SAMP" /* STDDEV_SAMP */]: "STDDEV_SAMP", ["VAR_POP" /* VAR_POP */]: "VAR_POP", ["VAR_SAMP" /* VAR_SAMP */]: "VAR_SAMP", ["MEDIAN" /* MEDIAN */]: "MEDIAN", ["MODE" /* MODE */]: "MODE" }); var PARSER_AGGREGATE_FUNCTIONS = Object.freeze( Object.values(PARSER_AGGREGATE_FUNCTION_TOKEN_MAP).filter( (func) => func !== void 0 ) ); var PARSER_AGGREGATE_WILDCARD_FUNCTIONS = Object.freeze([ "COUNT", "SUM", "AVG", "MAX", "MIN" ]); var PARSER_AGGREGATE_WILDCARD_FUNCTION_SET = new Set(PARSER_AGGREGATE_WILDCARD_FUNCTIONS); function aggregateAcceptsWildcard(func) { return PARSER_AGGREGATE_WILDCARD_FUNCTION_SET.has(func); } var PARSER_WINDOW_FUNCTION_TOKEN_MAP = Object.freeze({ ["ROW_NUMBER" /* ROW_NUMBER */]: "ROW_NUMBER", ["RANK" /* RANK */]: "RANK", ["DENSE_RANK" /* DENSE_RANK */]: "DENSE_RANK" }); var PARSER_CONTEXTUAL_FUNCTION_TOKEN_MAP = Object.freeze({ ["TODAY" /* TODAY */]: "TODAY", ["NOW" /* NOW */]: "NOW", ["LOGINUSER" /* LOGINUSER */]: "LOGINUSER" }); function isContextualFunctionToken(kind) { return PARSER_CONTEXTUAL_FUNCTION_TOKEN_MAP[kind] !== void 0; } var PARSER_FUNCTION_SPELLINGS = Object.freeze(Array.from(/* @__PURE__ */ new Set([ ...Object.keys(PARSER_SCALAR_FUNCTION_TOKEN_MAP), ...PARSER_IDENT_SCALAR_FUNCTIONS, ...Object.keys(PARSER_AGGREGATE_FUNCTION_TOKEN_MAP), ...Object.keys(PARSER_WINDOW_FUNCTION_TOKEN_MAP), ...Object.keys(PARSER_CONTEXTUAL_FUNCTION_TOKEN_MAP), "IF" ]))); var FUNC_CALL_PREFIX_KINDS = /* @__PURE__ */ new Set([ "IDENT" /* IDENT */, "BIDENT" /* BIDENT */, "COUNT" /* COUNT */, "SUM" /* SUM */, "AVG" /* AVG */, "MAX" /* MAX */, "MIN" /* MIN */, "GROUP_CONCAT" /* GROUP_CONCAT */, "STDDEV_POP" /* STDDEV_POP */, "STDDEV_SAMP" /* STDDEV_SAMP */, "VAR_POP" /* VAR_POP */, "VAR_SAMP" /* VAR_SAMP */, "MEDIAN" /* MEDIAN */, "MODE" /* MODE */, "ROW_NUMBER" /* ROW_NUMBER */, "RANK" /* RANK */, "DENSE_RANK" /* DENSE_RANK */, "TODAY" /* TODAY */, "NOW" /* NOW */, "LOGINUSER" /* LOGINUSER */, "UPPER" /* UPPER */, "LOWER" /* LOWER */, "TRIM" /* TRIM */, "LTRIM" /* LTRIM */, "RTRIM" /* RTRIM */, "LENGTH" /* LENGTH */, "LENGTH_CHAR" /* LENGTH_CHAR */, "SUBSTRING" /* SUBSTRING */, "SUBSTR" /* SUBSTR */, "CONCAT" /* CONCAT */, "REPLACE" /* REPLACE */, "TRANSLATE" /* TRANSLATE */, "COALESCE" /* COALESCE */, "NULLIF" /* NULLIF */, "ISNULL" /* ISNULL */, "REGEXP_LIKE" /* REGEXP_LIKE */, "REGEXP_REPLACE" /* REGEXP_REPLACE */, "REGEXP_SUBSTR" /* REGEXP_SUBSTR */, "LEFT" /* LEFT */, "RIGHT" /* RIGHT */, "INSTR" /* INSTR */, "GREATEST" /* GREATEST */, "LEAST" /* LEAST */, "LPAD" /* LPAD */, "RPAD" /* RPAD */, "CAST" /* CAST */, "CONVERT" /* CONVERT */, "FORMAT" /* FORMAT */, "ROUND" /* ROUND */, "FLOOR" /* FLOOR */, "CEIL" /* CEIL */, "CEILING" /* CEILING */, "TRUNCATE" /* TRUNCATE */, "TRUNC" /* TRUNC */, "ABS" /* ABS */, "MOD" /* MOD */, "POWER" /* POWER */, "POW" /* POW */, "SQRT" /* SQRT */, "YEAR" /* YEAR */, "MONTH" /* MONTH */, "DAY" /* DAY */, "DAYOFWEEK" /* DAYOFWEEK */, "QUARTER" /* QUARTER */, "WEEK" /* WEEK */, "DATE_FORMAT" /* DATE_FORMAT */, "DATEDIFF" /* DATEDIFF */, "DATE_ADD" /* DATE_ADD */, "LAST_DAY" /* LAST_DAY */, "IF" /* IF */ ]); function needsSpaceBetween(prev, cur) { if (prev.kind === "(" /* LPAREN */ || prev.kind === "." /* DOT */) return false; if (cur.kind === ")" /* RPAREN */ || cur.kind === "," /* COMMA */ || cur.kind === "." /* DOT */) return false; if (cur.kind === "(" /* LPAREN */) { return !FUNC_CALL_PREFIX_KINDS.has(prev.kind); } return true; } var ParseError = class extends Error { constructor(message, token) { super(`${message}\uFF08\u4F4D\u7F6E ${token.pos}\u3001\u30C8\u30FC\u30AF\u30F3: \u300C${token.value}\u300D\uFF09`); this.token = token; this.name = "ParseError"; } }; var Parser = class { constructor(tokens, capabilities = {}) { this.tokens = tokens; this.capabilities = capabilities; this.allowUnaryPlusNumber = false; this.scalarAllowsAggregateArgs = true; this.scalarAllowsCase = true; this.pos = 0; this.insideAggregateArg = 0; /** WITH 句で定義された CTE 名のセット(parseTableRef で参照) */ this.cteNames = /* @__PURE__ */ new Set(); /** パース中に出現した一時テーブル参照(#name)のトークン。単文 API での拒否に使う */ this.tempTableRefs = []; } // ---------------------------------------------------------- // 公開 API // ---------------------------------------------------------- /** 単文をパースする(従来 API。複文が渡されたらエラー) */ parse() { const stmts = this.parseStatements(); if (stmts.length === 0) { throw new ParseError("SQL \u6587\u304C\u3042\u308A\u307E\u305B\u3093", this.peek()); } if (stmts.length > 1) { throw new ParseError( "\u3053\u306E API \u306F\u5358\u6587\u306E\u307F\u53D7\u3051\u4ED8\u3051\u307E\u3059\uFF08\u8907\u6587\u306F\u30D0\u30C3\u30C1\u5B9F\u884C API \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\uFF09", this.peek() ); } if (this.tempTableRefs.length > 0) { const tok = this.tempTableRefs[0]; throw new ParseError( `temp table ${tok.value} is not defined in this batch.`, tok ); } return stmts[0]; } /** 複文(`;` 区切り)をパースする。空文はスキップする */ parseStatements() { const stmts = []; while (true) { while (this.peek().kind === ";" /* SEMICOLON */) this.advance(); if (this.peek().kind === "EOF" /* EOF */) break; const startTok = this.peek(); stmts.push(this.parseStatement()); if (stmts.length > MAX_BATCH_STATEMENTS) { throw new ParseError( `batch exceeds ${MAX_BATCH_STATEMENTS} statements.`, startTok ); } const after = this.peek(); if (after.kind !== ";" /* SEMICOLON */ && after.kind !== "EOF" /* EOF */) { throw new ParseError("\u6587\u306E\u533A\u5207\u308A\u306B\u306F ; \u304C\u5FC5\u8981\u3067\u3059", after); } } this.expect("EOF" /* EOF */); return stmts; } // ---------------------------------------------------------- // Statement ディスパッチ // ---------------------------------------------------------- parseStatement() { const tok = this.peek(); switch (tok.kind) { case "WITH" /* WITH */: return this.parseWith(); case "SELECT" /* SELECT */: return this.tryParseUnionChain(this.parseSelect(true)); case "INSERT" /* INSERT */: return this.parseInsert(); case "UPDATE" /* UPDATE */: return this.parseUpdate(); case "DELETE" /* DELETE */: return this.parseDelete(); case "REORDER" /* REORDER */: return this.parseReorder(); case "UPSERT" /* UPSERT */: return this.parseUpsert(); case "SHOW" /* SHOW */: return this.parseShow(); case "DESCRIBE" /* DESCRIBE */: case "DESC" /* DESC */: return this.parseDescribe(); case "EXPLAIN" /* EXPLAIN */: return this.parseExplain(); case "SET" /* SET */: return this.parseSetVariable(); case "ASSERT" /* ASSERT */: return this.parseAssert(); case "IDENT" /* IDENT */: { const upper = tok.value.toUpperCase(); if (upper === "CREATE") return this.parseCreateTempTable(); if (upper === "DROP") return this.parseDropTempTable(); if (upper === "DECLARE") return this.parseDeclareVariable(); if (upper === "VALIDATE") return this.parseValidate(); if (upper === "IMPORT") { if (!this.capabilities.import) { throw new ParseError("IMPORT is not supported (capability is disabled).", tok); } return this.parseImport(); } break; } default: break; } throw new ParseError( "SELECT / INSERT / UPDATE / DELETE / REORDER / VALIDATE / WITH / SHOW / DESCRIBE / EXPLAIN / CREATE TEMP TABLE / DROP TEMP TABLE / SET / DECLARE / ASSERT \u306E\u3044\u305A\u308C\u304B\u3067\u59CB\u307E\u308B SQL \u6587\u304C\u5FC5\u8981\u3067\u3059", tok ); } // ---------------------------------------------------------- // SET @name = // ---------------------------------------------------------- parseSetVariable() { this.expect("SET" /* SET */); const variable = this.expect("VARIABLE" /* VARIABLE */, "SET \u306E\u5F8C\u306B\u306F\u5909\u6570\u540D\uFF08\u4F8B: @name\uFF09\u304C\u5FC5\u8981\u3067\u3059"); this.expect("=" /* EQ */); const expr = this.peek().kind === "[" /* LBRACKET */ ? this.parseArrayLiteral() : this.parseScalarExpr("SET", true); return { type: "SET_VARIABLE", name: variable.value.slice(1).toLowerCase(), expr }; } parseDeclareVariable() { this.advance(); const variable = this.expect("VARIABLE" /* VARIABLE */, "DECLARE \u306E\u5F8C\u306B\u306F\u5909\u6570\u540D\uFF08\u4F8B: @name\uFF09\u304C\u5FC5\u8981\u3067\u3059"); this.expect("=" /* EQ */); const expr = this.parseScalarExpr("DECLARE", false); if (expr.type === "SCALAR_SUBQUERY") { throw new ParseError("DECLARE \u306E\u65E2\u5B9A\u5024\u306B\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } return { type: "DECLARE_VARIABLE", name: variable.value.slice(1).toLowerCase(), default: expr }; } /** SET / DECLARE RHS 専用。既存式パーサーで構文を読み、フィールド参照を明示的に拒否する。 */ parseScalarExpr(context, allowScalarSubquery) { const tok = this.peek(); if (tok.kind === "VARIABLE" /* VARIABLE */) { throw new ParseError(`${context} \u306E\u53F3\u8FBA\u3067\u306F\u4ED6\u306E\u5909\u6570\u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093`, tok); } if (tok.kind === "NULL" /* NULL */) { throw new ParseError(`${context} \u306E\u53F3\u8FBA\u3067 NULL \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093`, tok); } if (tok.kind === "(" /* LPAREN */ && this.peekAt(1).kind === "SELECT" /* SELECT */) { if (!allowScalarSubquery) { throw new ParseError("DECLARE \u306E\u65E2\u5B9A\u5024\u306B\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } this.advance(); const query = this.parseSelect(); this.expect(")" /* RPAREN */); if (this.isArithOp(this.peek().kind)) { throw new ParseError( "\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306E\u5F8C\u306B\u7B97\u8853\u6F14\u7B97\u5B50\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3057\u3066\u304F\u3060\u3055\u3044", this.peek() ); } const hasWildcard = query.columns.some( (c) => c.type === "WILDCARD" || c.type === "PARENT_WILDCARD" ); if (!hasWildcard && query.columns.length !== 1) { throw new ParseError("scalar subquery in SET must return exactly 1 column.", tok); } return { type: "SCALAR_SUBQUERY", query }; } if (tok.kind === "STRING" /* STRING */) { this.advance(); return { type: "STRING", value: tok.value }; } const contextualFunction = PARSER_CONTEXTUAL_FUNCTION_TOKEN_MAP[tok.kind]; if (contextualFunction === "LOGINUSER") { throw new ParseError( `${context} \u306E\u53F3\u8FBA\u3067 LOGINUSER() \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF08\u5B9F\u884C\u74B0\u5883\u5171\u901A\u306E\u30ED\u30B0\u30A4\u30F3\u30E6\u30FC\u30B6\u30FC\u89E3\u6C7A\u306F\u672A\u5BFE\u5FDC\u3067\u3059\uFF09`, tok ); } if (contextualFunction !== void 0) { return this.parseSqlValue(); } const expr = this.parseArithAddSub(); this.rejectNonScalarExpr(expr, tok, context); if (expr.type === "NUMBER" || expr.type === "STRING_FUNC" || expr.type === "ARITH") return expr; throw new ParseError(`${context} \u306E\u53F3\u8FBA\u306B\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3092\u542B\u307E\u306A\u3044\u30B9\u30AB\u30E9\u30FC\u5F0F\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`, tok); } rejectNonScalarExpr(node, tok, context) { if (node.type === "STRING" || node.type === "NUMBER") return; if (node.type === "FIELD_REF" || node.type === "FIELD" || node.type === "VARIABLE" || node.type === "AGG_REF") { throw new ParseError(`${context} \u306E\u53F3\u8FBA\u3067\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u30FB\u96C6\u8A08\u95A2\u6570\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093`, tok); } if (node.type === "ARITH" || node.type === "SCALAR_ARITH" || node.type === "CONCAT_OP" || node.type === "AGG_ARITH") { this.rejectNonScalarExpr(node.left, tok, context); this.rejectNonScalarExpr(node.right, tok, context); return; } if (node.type === "STRING_FUNC") { for (const arg of node.args) this.rejectNonScalarExpr(arg, tok, context); return; } throw new ParseError(`${context} \u306E\u53F3\u8FBA\u3067\u306F CASE \u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093`, tok); } // ---------------------------------------------------------- // CREATE TEMP TABLE / DROP TEMP TABLE(バッチ内一時テーブル) // CREATE / DROP / TEMP / TABLE は予約語にしない(ソフトキーワード) // ---------------------------------------------------------- parseCreateTempTable() { this.advance(); this.expectSoftKeyword("TEMP", "CREATE \u306E\u5F8C\u306B\u306F TEMP TABLE \u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: CREATE TEMP TABLE #temp AS SELECT ...\uFF09"); this.expectSoftKeyword("TABLE", "CREATE TEMP \u306E\u5F8C\u306B\u306F TABLE \u304C\u5FC5\u8981\u3067\u3059"); const name = this.parseTempTableName(); this.expect("AS" /* AS */, "CREATE TEMP TABLE \u306B\u306F AS SELECT \u304C\u5FC5\u8981\u3067\u3059"); const tok = this.peek(); let query; if (tok.kind === "WITH" /* WITH */) { query = this.parseWith(); } else if (tok.kind === "SELECT" /* SELECT */) { query = this.tryParseUnionChain(this.parseSelect()); } else { throw new ParseError("CREATE TEMP TABLE ... AS \u306E\u5F8C\u306B\u306F SELECT / WITH \u304C\u5FC5\u8981\u3067\u3059", tok); } return { type: "CREATE_TEMP_TABLE", name, query }; } parseDropTempTable() { this.advance(); this.expectSoftKeyword("TEMP", "DROP \u306E\u5F8C\u306B\u306F TEMP TABLE \u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: DROP TEMP TABLE #temp\uFF09"); this.expectSoftKeyword("TABLE", "DROP TEMP \u306E\u5F8C\u306B\u306F TABLE \u304C\u5FC5\u8981\u3067\u3059"); const name = this.parseTempTableName(); return { type: "DROP_TEMP_TABLE", name }; } expectSoftKeyword(word, msg) { const tok = this.peek(); if (tok.kind === "IDENT" /* IDENT */ && tok.value.toUpperCase() === word) { this.advance(); return; } throw new ParseError(msg, tok); } parseTempTableName() { const tok = this.peek(); if (tok.kind === "IDENT" /* IDENT */ && tok.value.startsWith("#")) { this.advance(); return tok.value; } throw new ParseError("\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\u306F # \u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF08\u4F8B: #temp\uFF09", tok); } parseShow() { this.advance(); if (!this.consume("APPS" /* APPS */)) { throw new ParseError("SHOW \u306E\u5F8C\u306B\u306F APPS \u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: SHOW APPS\uFF09", this.peek()); } return { type: "SHOW_APPS" }; } parseDescribe() { this.advance(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); if (subtableCode) { throw new ParseError("DESCRIBE \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u540D\u3092\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093", this.prev()); } return { type: "DESCRIBE", appId }; } parseExplain() { this.advance(); const tok = this.peek(); let query; if (tok.kind === "WITH" /* WITH */) { const w = this.parseWith(); if (w.type !== "WITH") { throw new ParseError("EXPLAIN \u306B\u7D9A\u304F WITH \u53E5\u304C\u4E0D\u6B63\u3067\u3059", tok); } query = w; } else if (tok.kind === "SELECT" /* SELECT */) { const sel = this.parseSelect(true); const chained = this.tryParseUnionChain(sel); query = chained; } else if (tok.kind === "INSERT" /* INSERT */) { query = this.parseInsert(); } else if (tok.kind === "UPSERT" /* UPSERT */) { query = this.parseUpsert(); } else if (tok.kind === "UPDATE" /* UPDATE */) { query = this.parseUpdate(); } else if (tok.kind === "DELETE" /* DELETE */) { query = this.parseDelete(); } else if (tok.kind === "REORDER" /* REORDER */) { query = this.parseReorder(); } else if (tok.kind === "IDENT" /* IDENT */ && tok.value.toUpperCase() === "VALIDATE") { query = this.parseValidate(); } else if (tok.kind === "IDENT" /* IDENT */ && tok.value.toUpperCase() === "IMPORT") { if (!this.capabilities.import) { throw new ParseError("IMPORT is not supported (capability is disabled).", tok); } query = this.parseImport(); } else { throw new ParseError("EXPLAIN \u306E\u5F8C\u306B\u306F SELECT / WITH / INSERT / UPSERT / UPDATE / DELETE / REORDER / VALIDATE \u304C\u5FC5\u8981\u3067\u3059", tok); } return { type: "EXPLAIN", query }; } parseImport() { this.advance(); let writeMode; if (this.peek().kind === "UPDATE" /* UPDATE */) { this.advance(); writeMode = "UPDATE_RECORD_NUMBER"; } this.expect("INTO" /* INTO */); this.rejectTempTableDml(); const target = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(target, this.prev()); if (subtableCode) throw new ParseError("IMPORT does not support subtables in Phase 1.", this.prev()); this.expect("(" /* LPAREN */); const targets = []; const fields = []; const targetNames = /* @__PURE__ */ new Set(); while (true) { const name = this.parseIdentifier(); if (targetNames.has(name)) throw new ParseError(`IMPORT target ${name} is declared more than once.`, this.prev()); targetNames.add(name); if (this.peek().kind === "(" /* LPAREN */) { this.advance(); const children = this.parseIdentList(); this.expect(")" /* RPAREN */); if (new Set(children).size !== children.length) { throw new ParseError(`IMPORT subtable ${name} contains duplicate child declarations.`, this.prev()); } let rowIdSourceHeader; if (this.isSoftKeyword("ROW")) { this.advance(); for (const word of ["ID", "SOURCE"]) { if (!this.isSoftKeyword(word)) throw new ParseError(`ROW must be followed by ID SOURCE
.`, this.peek()); this.advance(); } rowIdSourceHeader = this.parseIdentifier(); } targets.push({ kind: "SUBTABLE", subtableCode: name, children, ...rowIdSourceHeader ? { rowIdSourceHeader } : {} }); } else { fields.push(name); targets.push({ kind: "FIELD", field: name }); } if (this.peek().kind !== "," /* COMMA */) break; this.advance(); } this.expect(")" /* RPAREN */); this.expect("FROM" /* FROM */); if (!this.isSoftKeyword("CSV") && !this.isSoftKeyword("JSON")) throw new ParseError("IMPORT FROM requires CSV or JSON.", this.peek()); const sourceKind = this.peek().value.toUpperCase(); this.advance(); const sourceName = this.parseIdentifier(); let encoding; let hasHeader = true; let columns; if (this.isSoftKeyword("ENCODING")) { if (sourceKind === "JSON") throw new ParseError("JSON source is UTF-8 only; ENCODING is not allowed.", this.peek()); this.advance(); const value = this.parseIdentifier().toUpperCase(); if (value !== "UTF8" && value !== "SJIS") throw new ParseError("ENCODING must be UTF8 or SJIS.", this.prev()); encoding = value === "UTF8" ? "utf8" : "sjis"; } if (this.peek().kind === "NOT" /* NOT */ && this.peekAt(1).kind === "IDENT" /* IDENT */ && this.peekAt(1).value.toUpperCase() === "HEADER") { if (sourceKind === "JSON") throw new ParseError("NO HEADER is CSV-only.", this.peek()); this.advance(); this.advance(); hasHeader = false; } else if (this.isSoftKeyword("NO") && this.peekAt(1).kind === "IDENT" /* IDENT */ && this.peekAt(1).value.toUpperCase() === "HEADER") { if (sourceKind === "JSON") throw new ParseError("NO HEADER is CSV-only.", this.peek()); this.advance(); this.advance(); hasHeader = false; } if (this.isSoftKeyword("COLUMNS")) { if (sourceKind === "JSON") throw new ParseError("COLUMNS is CSV-only.", this.peek()); if (hasHeader) throw new ParseError("COLUMNS requires NO HEADER.", this.peek()); this.advance(); this.expect("(" /* LPAREN */); columns = this.parseIdentList(); this.expect(")" /* RPAREN */); } let projection; if (this.peek().kind === "SELECT" /* SELECT */) { if (sourceKind === "JSON") throw new ParseError("SELECT projection is CSV-only.", this.peek()); projection = this.parseSelect(); if (projection.from.cteName !== NO_FROM_CTE_NAME || projection.joins.length > 0) { throw new ParseError("IMPORT projection cannot use FROM or JOIN.", this.prev()); } if (projection.where || projection.groupBy.length || projection.having || projection.orderBy.length || projection.limit !== null || projection.offset !== null) { throw new ParseError("IMPORT projection supports SELECT expressions only.", this.prev()); } this.validateImportProjectionScope(projection, this.prev()); if (targets.some((item) => item.kind === "SUBTABLE")) { throw new ParseError("IMPORT subtable sources cannot use SELECT projection.", this.prev()); } if (projection.columns.length !== fields.length) { throw new ParseError(`IMPORT projection has ${projection.columns.length} columns; target has ${fields.length}.`, this.prev()); } } let mappingMode = "POSITION"; let ignoreUnknownColumns = false; if (this.peek().kind === "BY" /* BY */ || this.isSoftKeyword("BY")) { if (sourceKind === "JSON") throw new ParseError("BY NAME is CSV-only.", this.peek()); this.advance(); if (!this.isSoftKeyword("NAME")) throw new ParseError("BY must be followed by NAME in IMPORT.", this.peek()); this.advance(); if (!hasHeader) throw new ParseError("BY NAME requires HEADER.", this.prev()); if (projection) throw new ParseError("BY NAME and SELECT projection are mutually exclusive.", this.prev()); mappingMode = "BY_NAME"; if (this.isSoftKeyword("IGNORE")) { this.advance(); if (!this.isSoftKeyword("UNKNOWN")) throw new ParseError("IGNORE must be followed by UNKNOWN COLUMNS.", this.peek()); this.advance(); if (!this.isSoftKeyword("COLUMNS")) throw new ParseError("IGNORE UNKNOWN must be followed by COLUMNS.", this.peek()); this.advance(); ignoreUnknownColumns = true; } } let keyFields; let recordNumberSourceHeader; if (this.isSoftKeyword("MATCH")) { this.advance(); for (const word of ["RECORD", "NUMBER", "SOURCE"]) { if (!this.isSoftKeyword(word)) throw new ParseError(`MATCH must be followed by RECORD NUMBER SOURCE
.`, this.peek()); this.advance(); } recordNumberSourceHeader = this.parseIdentifier(); } if (this.peek().kind === "ON" /* ON */ && this.peekAt(1).kind === "DUPLICATE" /* DUPLICATE */) keyFields = this.parseOnDuplicate(); let replaceSubtables; if (this.peek().kind === "REPLACE" /* REPLACE */ || this.isSoftKeyword("REPLACE")) { this.advance(); if (!this.isSoftKeyword("SUBTABLES")) throw new ParseError("REPLACE must be followed by SUBTABLES (...).", this.peek()); this.advance(); this.expect("(" /* LPAREN */); replaceSubtables = this.parseIdentList(); this.expect(")" /* RPAREN */); if (new Set(replaceSubtables).size !== replaceSubtables.length) throw new ParseError("REPLACE SUBTABLES contains duplicates.", this.prev()); } const subtableTargets = targets.filter((item) => item.kind === "SUBTABLE"); if (subtableTargets.length) { if (projection) throw new ParseError("IMPORT subtables cannot use SELECT projection.", this.prev()); if (sourceKind === "JSON") { if (subtableTargets.some((item) => item.rowIdSourceHeader)) throw new ParseError("JSON subtable IMPORT does not accept ROW ID SOURCE.", this.prev()); if (replaceSubtables) throw new ParseError("REPLACE SUBTABLES is CSV-only; JSON uses nested-array replacement semantics.", this.prev()); } else { if (writeMode !== "UPDATE_RECORD_NUMBER" || !recordNumberSourceHeader) throw new ParseError("CSV subtable IMPORT requires IMPORT UPDATE and MATCH RECORD NUMBER SOURCE.", this.prev()); if (mappingMode !== "BY_NAME") throw new ParseError("CSV subtable IMPORT requires BY NAME.", this.prev()); if (!replaceSubtables) throw new ParseError("CSV subtable IMPORT requires REPLACE SUBTABLES (...).", this.prev()); const replacement = new Set(replaceSubtables); for (const item of subtableTargets) { if (!item.rowIdSourceHeader) throw new ParseError(`CSV subtable ${item.subtableCode} requires ROW ID SOURCE
.`, this.prev()); if (!replacement.has(item.subtableCode)) throw new ParseError(`IMPORT declares child columns for non-replaced subtable ${item.subtableCode}.`, this.prev()); } for (const code of replacement) { if (!subtableTargets.some((item) => item.subtableCode === code)) throw new ParseError(`REPLACE SUBTABLES target ${code} is not declared in INTO.`, this.prev()); } } } else if (replaceSubtables) { throw new ParseError("REPLACE SUBTABLES requires subtable targets in INTO.", this.prev()); } if (writeMode) { if (sourceKind !== "CSV") throw new ParseError("IMPORT UPDATE supports CSV only.", this.prev()); if (mappingMode !== "BY_NAME") throw new ParseError("IMPORT UPDATE requires BY NAME.", this.prev()); if (!recordNumberSourceHeader) throw new ParseError("IMPORT UPDATE requires MATCH RECORD NUMBER SOURCE
.", this.peek()); if (keyFields) throw new ParseError("IMPORT UPDATE and ON DUPLICATE are mutually exclusive.", this.prev()); } else if (recordNumberSourceHeader) { throw new ParseError("MATCH RECORD NUMBER SOURCE requires IMPORT UPDATE.", this.prev()); } const checkGroups = this.parseCheckGroups(); const control = this.parseDmlControlSuffix(); return { type: "IMPORT", appId, fields, targets, source: sourceKind === "JSON" ? { kind: "JSON", sourceName } : { kind: "CSV", sourceName, encoding, hasHeader, mappingMode, ignoreUnknownColumns, ...columns ? { columns } : {}, ...projection ? { projection } : {} }, ...writeMode ? { writeMode, recordNumberSourceHeader } : {}, ...replaceSubtables ? { replaceSubtables } : {}, ...keyFields ? { keyFields } : {}, ...checkGroups, ...control }; } validateImportProjectionScope(node, token) { if (Array.isArray(node)) { node.forEach((item) => this.validateImportProjectionScope(item, token)); return; } if (node === null || typeof node !== "object") return; const value = node; if (value.type === "SCALAR_SUBQUERY" || value.type === "SCALAR_SUBQUERY_COL") { throw new ParseError("IMPORT projection cannot use subqueries.", token); } if (typeof value.tableAlias === "string") { throw new ParseError("IMPORT projection cannot use qualified column references.", token); } Object.values(value).forEach((item) => this.validateImportProjectionScope(item, token)); } /** VALIDATE APP100 [(fields)] [WHERE ...] [CHECK ...] [INTO #err]. */ parseValidate() { const validateTok = this.advance(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); if (subtableCode) throw new ParseError( `VALIDATE APP${appId}$${subtableCode} \u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002VALIDATE APP${appId} (${subtableCode}) \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044`, this.prev() ); let targets; if (this.consume("(" /* LPAREN */)) { targets = []; do { const field = this.parseIdentifier(); if (this.consume("(" /* LPAREN */)) { const children = this.peek().kind === ")" /* RPAREN */ ? [] : this.parseIdentList(); this.expect(")" /* RPAREN */); targets.push({ kind: "SUBTABLE", subtableCode: field, children }); } else { targets.push({ kind: "FIELD", field }); } } while (this.consume("," /* COMMA */)); this.expect(")" /* RPAREN */); } let summary; if (this.isSoftKeyword("SUMMARY")) { this.advance(); summary = true; } const where = this.consume("WHERE" /* WHERE */) ? this.parseWhereExpr() : null; const checks = this.parseCheckGroups(); let errorTable; if (this.consume("INTO" /* INTO */)) { const tableTok = this.peek(); if (tableTok.kind !== "IDENT" /* IDENT */ || !tableTok.value.startsWith("#")) { throw new ParseError("VALIDATE INTO \u306B\u306F # \u3067\u59CB\u307E\u308B\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\u304C\u5FC5\u8981\u3067\u3059", tableTok); } errorTable = this.parseTableName(); } const stmt = { type: "VALIDATE", appId, targets, ...summary ? { summary } : {}, where, ...checks, ...errorTable ? { errorTable } : {} }; this.assertValidateExpressions(stmt, validateTok); return stmt; } /** v1 VALIDATE is single-app/local: subqueries and qualified references are rejected. */ assertValidateExpressions(stmt, tok) { const visit = (node) => { if (Array.isArray(node)) { node.forEach(visit); return; } if (node === null || typeof node !== "object") return; const obj = node; if (obj.type === "EXISTS" || obj.type === "SUBQUERY_IN_LIST" || obj.type === "SCALAR_SUBQUERY") { throw new ParseError("VALIDATE \u306E WHERE / CHECK \u306B\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } if (obj.type === "FIELD" && obj.tableAlias !== null && obj.tableAlias !== void 0) { throw new ParseError("VALIDATE \u306E WHERE / CHECK \u3067\u306F\u4FEE\u98FE\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } if (obj.type === "FIELD_REF" && typeof obj.field === "string" && obj.field.includes(".")) { throw new ParseError("VALIDATE \u306E WHERE / CHECK \u3067\u306F\u4FEE\u98FE\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } Object.values(obj).forEach(visit); }; visit(stmt.where); visit(stmt.checkGroups); } // ---------------------------------------------------------- // ASSERT // // ASSERT <式> <比較演算子> <式> // ASSERT <式> BETWEEN <式> AND <式> // // 式: リテラル / 算術式 / スカラーサブクエリ。 // フィールド参照(FROM コンテキストがない)・AND / OR 複合条件・ // 裸の値のみ(ASSERT 1)は ParseError。 // ---------------------------------------------------------- parseAssert() { this.expect("ASSERT" /* ASSERT */); const condStart = this.pos; const left = this.parseAssertOperand(); const opTok = this.peek(); if (this.consume("BETWEEN" /* BETWEEN */)) { const low = this.parseAssertOperand(); this.expect( "AND" /* AND */, "ASSERT \u306E BETWEEN \u306B\u306F AND \u304C\u5FC5\u8981\u3067\u3059\uFF08\u4F8B: ASSERT (SELECT COUNT(*) FROM #t) BETWEEN 1 AND 500\uFF09" ); const high = this.parseAssertOperand(); this.rejectAssertCompound(); return { type: "ASSERT", left, op: "BETWEEN", right: null, low, high, text: this.renderTokenRange(condStart, this.pos) }; } const op = this.tryAssertCompareOp(); if (op === null) { throw new ParseError( "ASSERT \u306B\u306F\u6BD4\u8F03\u6F14\u7B97\u5B50\uFF08= <> < <= > >=\uFF09\u307E\u305F\u306F BETWEEN \u304C\u5FC5\u8981\u3067\u3059\uFF08\u5024\u306E\u307F\u306E ASSERT \u306F\u4E0D\u53EF\uFF09", opTok ); } const right = this.parseAssertOperand(); this.rejectAssertCompound(); return { type: "ASSERT", left, op, right, low: null, high: null, text: this.renderTokenRange(condStart, this.pos) }; } /** ASSERT のオペランド: 文字列 / スカラーサブクエリ / 数値算術式 */ parseAssertOperand() { const tok = this.peek(); if (tok.kind === "VARIABLE" /* VARIABLE */) { this.advance(); return { type: "VARIABLE", name: tok.value.slice(1).toLowerCase() }; } if (tok.kind === "STRING" /* STRING */) { this.advance(); return { type: "STRING", value: tok.value }; } if (tok.kind === "(" /* LPAREN */ && this.peekAt(1).kind === "SELECT" /* SELECT */) { this.advance(); const query = this.parseSelect(); this.expect(")" /* RPAREN */); if (this.isArithOp(this.peek().kind)) { throw new ParseError( "\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306E\u5F8C\u306B\u7B97\u8853\u6F14\u7B97\u5B50\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u4F8B: ASSERT (SELECT COUNT(*) * 2 FROM APP100) > 10\uFF09", this.peek() ); } const hasWildcard = query.columns.some( (c) => c.type === "WILDCARD" || c.type === "PARENT_WILDCARD" ); if (!hasWildcard && query.columns.length > 1) { throw new ParseError("scalar subquery in ASSERT must return exactly 1 column.", tok); } return { type: "SCALAR_SUBQUERY", query }; } if (tok.kind === "NUMBER" /* NUMBER */ || tok.kind === "(" /* LPAREN */ || tok.kind === "-" /* MINUS */) { const expr = this.parseArithAddSub(); this.rejectNonLiteralArith(expr, tok); if (expr.type === "NUMBER") return expr; return expr; } if (this.tryStringFuncName() !== null) { throw new ParseError( "ASSERT \u306E\u5F0F\u3067\u306F\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF08\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3057\u3066\u304F\u3060\u3055\u3044\uFF09", tok ); } throw new ParseError( "ASSERT \u306E\u5F0F\u306B\u306F\u30EA\u30C6\u30E9\u30EB\u30FB\u7B97\u8853\u5F0F\u30FB\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF09", tok ); } /** ASSERT の算術式にフィールド参照・関数呼び出しが含まれていたら拒否する */ rejectNonLiteralArith(node, tok) { if (node.type === "FIELD_REF") { throw new ParseError( `ASSERT \u3067\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF08FROM \u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u304C\u3042\u308A\u307E\u305B\u3093\uFF09: ${node.field}`, tok ); } if (node.type === "STRING_FUNC") { throw new ParseError( "ASSERT \u306E\u5F0F\u3067\u306F\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\uFF08\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3057\u3066\u304F\u3060\u3055\u3044\uFF09", tok ); } if (node.type === "ARITH") { this.rejectNonLiteralArith(node.left, tok); this.rejectNonLiteralArith(node.right, tok); } } /** ASSERT の比較演算子を読む(該当しなければ null・消費しない) */ tryAssertCompareOp() { switch (this.peek().kind) { case "=" /* EQ */: this.advance(); return "="; case "!=" /* NEQ */: this.advance(); return "!="; case "<>" /* LT_GT */: this.advance(); return "<>"; case ">" /* GT */: this.advance(); return ">"; case "<" /* LT */: this.advance(); return "<"; case ">=" /* GTE */: this.advance(); return ">="; case "<=" /* LTE */: this.advance(); return "<="; default: return null; } } /** ASSERT は AND / OR による複合条件に対応しない(初期版仕様) */ rejectAssertCompound() { const tok = this.peek(); if (tok.kind === "AND" /* AND */ || tok.kind === "OR" /* OR */) { throw new ParseError( "ASSERT \u306F AND / OR \u306B\u3088\u308B\u8907\u5408\u6761\u4EF6\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093\uFF08\u8907\u6570\u306E ASSERT \u6587\u306B\u5206\u3051\u3066\u304F\u3060\u3055\u3044\uFF09", tok ); } } /** * トークン列 [fromIdx, toIdx) を SQL 風テキストに再構成する。 * AssertError の "assertion failed: <条件>" メッセージ用(正規化表示で十分)。 */ renderTokenRange(fromIdx, toIdx) { let out = ""; for (let i = fromIdx; i < toIdx; i++) { const t = this.tokens[i]; let text; if (t.kind === "STRING" /* STRING */) text = `'${t.value.replace(/'/g, "''")}'`; else if (t.kind === "BIDENT" /* BIDENT */) text = `\`${t.value}\``; else text = t.value; if (out.length > 0 && needsSpaceBetween(this.tokens[i - 1], t)) out += " "; out += text; } return out; } // ---------------------------------------------------------- // SELECT // ---------------------------------------------------------- parseSelect(allowKorder = false) { this.expect("SELECT" /* SELECT */); const distinct = this.consume("DISTINCT" /* DISTINCT */); const columns = this.parseSelectColumns(); const hasFrom = this.consume("FROM" /* FROM */); const from = hasFrom ? this.parseTableRef() : { appId: 0, alias: null, cteName: NO_FROM_CTE_NAME }; const joins = hasFrom ? this.parseJoins() : []; const where = this.consume("WHERE" /* WHERE */) ? this.parseWhereExpr() : null; let groupBy = []; let having = null; if (this.consume("GROUP" /* GROUP */)) { this.expect("BY" /* BY */); groupBy = this.parseGroupByKeys(); if (this.consume("HAVING" /* HAVING */)) { having = this.parseWhereExpr(); } } let orderMode = "CANONICAL"; let orderBy = []; if (this.consume("ORDER" /* ORDER */)) { this.expect("BY" /* BY */); orderBy = this.parseOrderBy(); } else if (this.consume("KORDER" /* KORDER */)) { if (!allowKorder) { throw new ParseError("KORDER BY \u306F\u5229\u7528\u8005\u3078\u7D50\u679C\u3092\u8FD4\u3059\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB SELECT \u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059", this.prev()); } orderMode = "KINTONE_NATIVE"; this.expect("BY" /* BY */); orderBy = this.parseOrderBy(); } const limit = this.consume("LIMIT" /* LIMIT */) ? this.parseUnsignedInt() : null; const offset = this.consume("OFFSET" /* OFFSET */) ? this.parseUnsignedInt() : null; const hasWindow = columns.some((column) => column.type === "WINDOW_COL"); const hasAggregate = columns.some((column) => this.selectColumnHasAggregate(column)); if (hasWindow && (groupBy.length > 0 || hasAggregate)) { throw new ParseError("\u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570\u306F GROUP BY / \u96C6\u8A08\u95A2\u6570\u3068\u540C\u3058 SELECT \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } return { type: "SELECT", distinct, columns, from, joins, where, groupBy, having, orderMode, orderBy, limit, offset }; } // ---------------------------------------------------------- // WITH 句(CTE) // ---------------------------------------------------------- parseWith() { this.expect("WITH" /* WITH */); const ctes = []; do { const name = this.parseIdentifier(); this.expect("AS" /* AS */); this.expect("(" /* LPAREN */); let query2; const inner = this.peek().kind; if (inner === "SHOW" /* SHOW */) { query2 = this.parseShow(); } else if (inner === "DESCRIBE" /* DESCRIBE */ || inner === "DESC" /* DESC */) { query2 = this.parseDescribe(); } else { query2 = this.tryParseUnionChain(this.parseSelect()); } this.expect(")" /* RPAREN */); ctes.push({ name, query: query2 }); this.cteNames.add(name); } while (this.consume("," /* COMMA */)); const query = this.tryParseUnionChain(this.parseSelect()); this.cteNames.clear(); return { type: "WITH", ctes, query }; } // ---------------------------------------------------------- // UNION / UNION ALL チェーン // ---------------------------------------------------------- tryParseUnionChain(left) { if (this.peek().kind !== "UNION" /* UNION */) return left; if (left.type === "SELECT" && left.orderMode === "KINTONE_NATIVE") { throw new ParseError("KORDER BY \u306F UNION \u5206\u5C90\u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } this.advance(); const all = this.consume("ALL" /* ALL */); const right = this.parseSelect(); const union2 = { type: "UNION", all, left, right }; return this.tryParseUnionChain(union2); } // SELECT 句のカラムリスト parseSelectColumns() { const cols = []; do { cols.push(this.parseSelectColumn()); } while (this.consume("," /* COMMA */)); return cols; } parseSelectColumn() { if (this.consume("*" /* STAR */)) { return { type: "WILDCARD" }; } if (this.tryAggregateFunc() === null && this.hasTopLevelTokenBeforeValueEnd("||" /* CONCAT_OP */)) { const expr = this.parseScalarValueExpr({ allowAggregateArgs: true }); const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "SCALAR_VALUE_COL", expr, alias: alias2 }; } if (this.peek().kind === "VARIABLE" /* VARIABLE */) { const variable = this.advance(); if (!this.consume("AS" /* AS */)) { throw new ParseError("SELECT \u5217\u306E\u30D0\u30C3\u30C1\u5909\u6570\u306B\u306F AS alias \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } return { type: "VARIABLE_COL", name: variable.value.slice(1).toLowerCase(), alias: this.parseAliasName() }; } const windowFunc = this.tryWindowFunc(); if (windowFunc !== null) { return this.parseWindowColumn(windowFunc); } if (this.peek().kind === "CASE" /* CASE */) { const expr = this.parseCaseWhenExpr(); const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "CASE_COL", expr, alias: alias2 }; } if (this.peek().kind === "IF" /* IF */) { const expr = this.parseIfExpr(); const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "CASE_COL", expr, alias: alias2 }; } if (this.tryStringFuncName() !== null) { const funcExpr = this.parseStringFuncExpr(); if (this.isArithOp(this.peek().kind)) { const node = this.continueArith(funcExpr); const alias3 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "ARITH_COL", expr: node, alias: alias3 }; } const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "STRFUNC_COL", expr: funcExpr, alias: alias2 }; } const aggFunc = this.tryAggregateFunc(); if (aggFunc !== null) { const ref = this.parseAggregateRef(aggFunc); if (this.isArithOp(this.peek().kind)) { const expr = this.continueAggArith(ref); const alias3 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "ARITH_AGG_COL", expr, alias: alias3 }; } const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "AGGREGATE", func: ref.func, distinct: ref.distinct, arg: ref.arg, ...ref.separator !== void 0 ? { separator: ref.separator } : {}, alias: alias2 }; } if (this.peek().kind === "(" /* LPAREN */ && this.peekAt(1).kind === "SELECT" /* SELECT */) { this.advance(); const query = this.parseSelect(); this.expect(")" /* RPAREN */); const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "SCALAR_SUBQUERY_COL", query, alias: alias2 }; } if (this.peek().kind === "STRING" /* STRING */) { const value = this.expect("STRING" /* STRING */).value; const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "LITERAL_COL", value, alias: alias2 }; } if (this.peek().kind === "(" /* LPAREN */ || this.peek().kind === "NUMBER" /* NUMBER */) { const node = this.parseArithAddSub(); const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "ARITH_COL", expr: node, alias: alias2 }; } const field = this.parseColumnFieldRef(); if (field === "_p.*") { return { type: "PARENT_WILDCARD" }; } if (field === "_parent.*") { throw new ParseError("_parent.* \u306F\u5EC3\u6B62\u3057\u307E\u3057\u305F\u3002_p.* \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044", this.prev()); } if (this.isArithOp(this.peek().kind)) { const left = { type: "FIELD_REF", field }; const node = this.continueArith(left); const alias2 = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "ARITH_COL", expr: node, alias: alias2 }; } const alias = this.consume("AS" /* AS */) ? this.parseAliasName() : null; return { type: "FIELD", field, alias }; } tryWindowFunc() { return PARSER_WINDOW_FUNCTION_TOKEN_MAP[this.peek().kind] ?? null; } parseWindowColumn(func) { this.advance(); this.expect("(" /* LPAREN */); if (this.peek().kind !== ")" /* RPAREN */) { throw new ParseError(`${func} \u306F\u5F15\u6570\u3092\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093`, this.peek()); } this.expect(")" /* RPAREN */); this.expectSoftKeyword("OVER", `${func} \u306B\u306F OVER (...) \u304C\u5FC5\u8981\u3067\u3059`); this.expect("(" /* LPAREN */); const partitionBy = []; if (this.isSoftKeyword("PARTITION")) { this.advance(); this.expect("BY" /* BY */, "PARTITION \u306E\u5F8C\u306B\u306F BY \u304C\u5FC5\u8981\u3067\u3059"); do { const ref = this.parseQualifiedIdent(); partitionBy.push({ type: "FIELD", tableAlias: ref.tableAlias, field: ref.field }); } while (this.consume("," /* COMMA */)); } const orderBy = this.consume("ORDER" /* ORDER */) ? (this.expect("BY" /* BY */), this.parseOrderBy()) : []; this.expect(")" /* RPAREN */); if (!this.consume("AS" /* AS */)) { throw new ParseError("\u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570\u306B\u306F AS alias \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } const alias = this.parseAliasName(); return { type: "WINDOW_COL", func, partitionBy, orderBy, alias }; } selectColumnHasAggregate(column) { if (column.type === "AGGREGATE" || column.type === "ARITH_AGG_COL") return true; if (column.type === "STRFUNC_COL") return column.expr.args.some((arg) => this.stringFuncArgHasAggregate(arg)); if (column.type === "SCALAR_VALUE_COL") return this.scalarValueHasAggregate(column.expr); return false; } stringFuncArgHasAggregate(arg) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") return true; return this.scalarValueHasAggregate(arg); } scalarValueHasAggregate(expr) { if (expr.type === "STRING_FUNC") return expr.args.some((arg) => this.stringFuncArgHasAggregate(arg)); if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { return this.scalarValueHasAggregate(expr.left) || this.scalarValueHasAggregate(expr.right); } if (expr.type === "CASE_WHEN") { const results = [...expr.branches.map((b) => b.result), ...expr.elseResult ? [expr.elseResult] : []]; return results.some((result) => { if (result.type === "ARRAY" || result.type === "FIELD_REF" || result.type === "ARITH") return false; return this.scalarValueHasAggregate(result); }); } return false; } isArithOp(kind) { return kind === "+" /* PLUS */ || kind === "-" /* MINUS */ || kind === "*" /* STAR */ || kind === "/" /* SLASH */ || kind === "%" /* PERCENT */; } // ────────────────────────────────────────────────── // 集計算術式パーサー // // continueAggArith : + - > * / // └ continueAggArithMulDiv : * / // └ parseAggPrimary : 集計関数 / 数値 / (expr) // ────────────────────────────────────────────────── continueAggArith(left) { return this.continueAggArithAddSub(this.continueAggArithMulDiv(left)); } continueAggArithMulDiv(left) { while (this.peek().kind === "*" /* STAR */ || this.peek().kind === "/" /* SLASH */ || this.peek().kind === "%" /* PERCENT */) { const op = this.parseArithOp(); left = { type: "AGG_ARITH", left, op, right: this.parseAggPrimary() }; } return left; } continueAggArithAddSub(left) { while (this.peek().kind === "+" /* PLUS */ || this.peek().kind === "-" /* MINUS */) { const op = this.parseArithOp(); left = { type: "AGG_ARITH", left, op, right: this.parseAggArithMulDiv() }; } return left; } parseAggArithMulDiv() { return this.continueAggArithMulDiv(this.parseAggPrimary()); } /** 集計算術式の一次式: 集計関数 / 数値リテラル / 括弧 */ parseAggPrimary() { if (this.consume("(" /* LPAREN */)) { const inner = this.continueAggArith(this.parseAggPrimary()); this.expect(")" /* RPAREN */); return inner; } if (this.peek().kind === "-" /* MINUS */) { this.advance(); const operand = this.parseAggPrimary(); if (operand.type === "NUMBER") return makeNumberLiteral(`-${numberLiteralText(operand)}`); return { type: "AGG_ARITH", left: makeNumberLiteral("0"), op: "-", right: operand }; } if (this.peek().kind === "NUMBER" /* NUMBER */) { const tok = this.advance(); return makeNumberLiteral(tok.value); } const aggFunc = this.tryAggregateFunc(); if (aggFunc !== null) { return this.parseAggregateRef(aggFunc); } throw new ParseError("\u96C6\u8A08\u7B97\u8853\u5F0F\u306B\u306F\u96C6\u8A08\u95A2\u6570\u307E\u305F\u306F\u6570\u5024\u304C\u5FC5\u8981\u3067\u3059", this.peek()); } // ────────────────────────────────────────────────── // 汎用スカラー値式パーサー(B38) // ────────────────────────────────────────────────── /** 比較・述語・集約・サブクエリを含まない値式の公開入口。 */ parseScalarValueExpr(options = {}) { const previousAggregateArgs = this.scalarAllowsAggregateArgs; const previousCase = this.scalarAllowsCase; this.scalarAllowsAggregateArgs = options.allowAggregateArgs === true; this.scalarAllowsCase = options.allowCase !== false; let expr; try { expr = this.parseScalarAddSubConcat(this.scalarAllowsCase); } finally { this.scalarAllowsAggregateArgs = previousAggregateArgs; this.scalarAllowsCase = previousCase; } const next = this.peek(); if (next.kind === "IS" /* IS */ || next.kind === "=" /* EQ */ || next.kind === "!=" /* NEQ */ || next.kind === "<>" /* LT_GT */ || next.kind === ">" /* GT */ || next.kind === "<" /* LT */ || next.kind === ">=" /* GTE */ || next.kind === "<=" /* LTE */ || next.kind === "LIKE" /* LIKE */ || next.kind === "KLIKE" /* KLIKE */ || next.kind === "IN" /* IN */ || next.kind === "BETWEEN" /* BETWEEN */) throw new ParseError("\u30B9\u30AB\u30E9\u30FC\u5024\u5F0F\u306B\u6BD4\u8F03\u30FB\u8FF0\u8A9E\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", next); return expr; } parseScalarAddSubConcat(allowCase) { let left = this.parseScalarMulDiv(allowCase); while (this.peek().kind === "+" /* PLUS */ || this.peek().kind === "-" /* MINUS */ || this.peek().kind === "||" /* CONCAT_OP */) { const token = this.advance(); const right = this.parseScalarMulDiv(allowCase); left = token.kind === "||" /* CONCAT_OP */ ? { type: "CONCAT_OP", left, right } : { type: "SCALAR_ARITH", left, op: token.kind === "+" /* PLUS */ ? "+" : "-", right }; } return left; } parseScalarMulDiv(allowCase) { let left = this.parseScalarPrimary(allowCase); while (this.peek().kind === "*" /* STAR */ || this.peek().kind === "/" /* SLASH */ || this.peek().kind === "%" /* PERCENT */) { const token = this.advance(); const op = token.kind === "*" /* STAR */ ? "*" : token.kind === "/" /* SLASH */ ? "/" : "%"; left = { type: "SCALAR_ARITH", left, op, right: this.parseScalarPrimary(allowCase) }; } return left; } parseScalarPrimary(allowCase) { const tok = this.peek(); if (tok.kind === "(" /* LPAREN */) { if (this.peekAt(1).kind === "SELECT" /* SELECT */) throw new ParseError("\u30B9\u30AB\u30E9\u30FC\u5024\u5F0F\u306B\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); this.advance(); const expr = this.parseScalarAddSubConcat(allowCase); this.expect(")" /* RPAREN */); return expr; } if (tok.kind === "+" /* PLUS */ || tok.kind === "-" /* MINUS */) { this.advance(); if (this.peek().kind === "+" /* PLUS */ || this.peek().kind === "-" /* MINUS */) { throw new ParseError("\u5358\u9805\u7B26\u53F7\u3092\u91CD\u306D\u3066\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093", this.peek()); } const operand = this.parseScalarPrimary(allowCase); if (operand.type === "NUMBER") { return makeNumberLiteral(`${tok.kind === "-" /* MINUS */ ? "-" : "+"}${numberLiteralText(operand)}`); } if (tok.kind === "+" /* PLUS */) throw new ParseError("\u5358\u9805 + \u306E\u76F4\u5F8C\u306B\u306F\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059", tok); return { type: "SCALAR_ARITH", left: makeNumberLiteral("0"), op: "-", right: operand }; } if (tok.kind === "STRING" /* STRING */) { this.advance(); return { type: "STRING", value: tok.value }; } if (tok.kind === "NUMBER" /* NUMBER */) { this.advance(); return makeNumberLiteral(tok.value); } if (tok.kind === "VARIABLE" /* VARIABLE */) { this.advance(); return { type: "VARIABLE", name: tok.value.slice(1).toLowerCase() }; } if (tok.kind === "CASE" /* CASE */) { if (!allowCase) throw new ParseError("\u3053\u306E\u30B9\u30AB\u30E9\u30FC\u5024\u5F0F\u3067\u306F CASE \u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); return this.parseCaseWhenExpr(); } if (this.tryAggregateFunc() !== null) { throw new ParseError( this.insideAggregateArg > 0 ? "\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u5185\u306B\u96C6\u8A08\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" : "\u30B9\u30AB\u30E9\u30FC\u5024\u5F0F\u306B\u96C6\u7D04\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok ); } if (this.tryStringFuncName() !== null) return this.parseStringFuncExpr(); if (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) { this.advance(); if (this.consume("." /* DOT */)) return { type: "FIELD", tableAlias: tok.value, field: this.parseIdentifier() }; return { type: "FIELD", tableAlias: null, field: tok.value }; } throw new ParseError("\u30B9\u30AB\u30E9\u30FC\u5024\u5F0F\u306E\u30AA\u30DA\u30E9\u30F3\u30C9\u304C\u5FC5\u8981\u3067\u3059", tok); } /** 現在の値の終端までに指定トークンがあるか(括弧内も対象)。 */ hasTopLevelTokenBeforeValueEnd(target) { let depth = 0; for (let i = this.pos; i < this.tokens.length; i++) { const kind = this.tokens[i].kind; if (kind === "(" /* LPAREN */ || kind === "[" /* LBRACKET */) depth++; else if (kind === ")" /* RPAREN */ || kind === "]" /* RBRACKET */) { if (depth === 0) break; depth--; } if (kind === target) return true; if (depth === 0 && (kind === "," /* COMMA */ || kind === "AS" /* AS */ || kind === "FROM" /* FROM */ || kind === "WHERE" /* WHERE */ || kind === "WHEN" /* WHEN */ || kind === "THEN" /* THEN */ || kind === "ELSE" /* ELSE */ || kind === "END" /* END */ || kind === ";" /* SEMICOLON */ || kind === "EOF" /* EOF */)) break; } return false; } // ────────────────────────────────────────────────── // 算術式パーサー(演算子優先順位: * / > + -) // // parseArithAddSub : + -(左結合・低優先度) // └ parseArithMulDiv : * /(左結合・高優先度) // └ parseArithPrimary : 数値 / フィールド / (expr) // // continueArith*(left) は先頭の primary を外部で読んだ場合に使う // ────────────────────────────────────────────────── parseArithAddSub() { return this.continueArithAddSub(this.parseArithMulDiv()); } parseArithMulDiv() { return this.continueArithMulDiv(this.parseArithPrimary()); } /** 左辺が決まっている状態から残りを解析(SELECT column など) */ continueArith(left) { return this.continueArithAddSub(this.continueArithMulDiv(left)); } continueArithMulDiv(left) { while (this.peek().kind === "*" /* STAR */ || this.peek().kind === "/" /* SLASH */ || this.peek().kind === "%" /* PERCENT */) { const op = this.parseArithOp(); const right = this.parseArithPrimary(); left = { type: "ARITH", left, op, right }; } return left; } continueArithAddSub(left) { while (this.peek().kind === "+" /* PLUS */ || this.peek().kind === "-" /* MINUS */) { const op = this.parseArithOp(); const right = this.parseArithMulDiv(); left = { type: "ARITH", left, op, right }; } return left; } parseArithPrimary() { if (this.consume("(" /* LPAREN */)) { const expr = this.parseArithAddSub(); this.expect(")" /* RPAREN */); return expr; } if (this.allowUnaryPlusNumber && this.peek().kind === "+" /* PLUS */) { this.advance(); const number4 = this.expect("NUMBER" /* NUMBER */, "\u5358\u9805 + \u306E\u76F4\u5F8C\u306B\u306F\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059"); return makeNumberLiteral(`+${number4.value}`); } if (this.peek().kind === "-" /* MINUS */) { this.advance(); if (this.peek().kind === "-" /* MINUS */ || this.peek().kind === "+" /* PLUS */) { throw new ParseError("\u5358\u9805\u7B26\u53F7\u3092\u91CD\u306D\u3066\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093", this.peek()); } const operand = this.parseArithPrimary(); if (operand.type === "NUMBER") return makeNumberLiteral(`-${numberLiteralText(operand)}`); return { type: "ARITH", left: makeNumberLiteral("0"), op: "-", right: operand }; } if (this.tryStringFuncName() !== null) { return this.parseStringFuncExpr(); } const tok = this.peek(); if (tok.kind === "NUMBER" /* NUMBER */) { this.advance(); return makeNumberLiteral(tok.value); } if (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) { this.advance(); let field = tok.value; if (this.peek().kind === "." /* DOT */) { this.advance(); const fieldTok = this.advance(); field = `${field}.${fieldTok.value}`; } return { type: "FIELD_REF", field }; } throw new ParseError( "\u7B97\u8853\u5F0F\u306E\u30AA\u30DA\u30E9\u30F3\u30C9\u306B\u306F\u8B58\u5225\u5B50\u30FB\u6570\u5024\u30FB\u62EC\u5F27\u5F0F\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", tok ); } // ────────────────────────────────────────────────── // CASE WHEN 式パーサー // // CASE WHEN cond THEN result [WHEN cond THEN result]... [ELSE result] END // // cond : WhereExpr(WHERE 句と同じ文法) // result: 文字列リテラル / 算術式(フィールド参照・数値含む) // ────────────────────────────────────────────────── /** IF(条件, then値, else値) → CaseWhenExpr に変換 */ parseIfExpr() { this.advance(); this.expect("(" /* LPAREN */); const condition = this.parseWhereExpr(); this.expect("," /* COMMA */); const thenResult = this.parseCaseResult(); this.expect("," /* COMMA */); const elseResult = this.parseCaseResult(); this.expect(")" /* RPAREN */); return { type: "CASE_WHEN", branches: [{ condition, result: thenResult }], elseResult }; } parseCaseWhenExpr() { this.expect("CASE" /* CASE */); const branches = []; while (this.peek().kind === "WHEN" /* WHEN */) { this.advance(); const condition = this.parseWhereExpr(); this.expect("THEN" /* THEN */); const result = this.parseCaseResult(); branches.push({ condition, result }); } if (branches.length === 0) { throw new ParseError("CASE \u306E\u5F8C\u306B\u306F WHEN \u304C\u6700\u4F4E 1 \u3064\u5FC5\u8981\u3067\u3059", this.peek()); } let elseResult = null; if (this.consume("ELSE" /* ELSE */)) { elseResult = this.parseCaseResult(); } this.expect("END" /* END */); return { type: "CASE_WHEN", branches, elseResult }; } /** THEN / ELSE の結果値。`||` を含む場合だけ新スカラー文法へ渡す。 */ parseCaseResult() { const tok = this.peek(); if (this.insideAggregateArg > 0 && this.tryAggregateFunc() !== null) { throw new ParseError("\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u5185\u306B\u96C6\u8A08\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } if (tok.kind === "[" /* LBRACKET */) { return this.parseArrayLiteral(); } if (this.hasTopLevelTokenBeforeValueEnd("||" /* CONCAT_OP */)) { return this.parseScalarValueExpr({ allowAggregateArgs: true }); } if (tok.kind === "STRING" /* STRING */) { this.advance(); return { type: "STRING", value: tok.value }; } if (this.tryStringFuncName() !== null) { return this.parseStringFuncExpr(); } return this.parseArithAddSub(); } // ────────────────────────────────────────────────── // 文字列関数パーサー // // UPPER(arg) / LOWER(arg) / TRIM(arg) / LTRIM(arg) / RTRIM(arg) // LENGTH(arg) // SUBSTRING(arg, start [, len]) / SUBSTR(arg, start [, len]) // CONCAT(arg1, arg2, ...) // REPLACE(arg, from, to) // // arg: 文字列リテラル / 算術式(フィールド参照・数値含む)/ ネスト文字列関数 // ────────────────────────────────────────────────── tryStringFuncName() { if (this.peekAt(1).kind === "(" /* LPAREN */) { const conditional = PARSER_SCALAR_FUNCTION_TOKEN_MAP[this.peek().kind]; if (conditional === "LEFT" || conditional === "RIGHT") return conditional; } const byKind = PARSER_SCALAR_FUNCTION_TOKEN_MAP[this.peek().kind] ?? null; if (byKind !== null && byKind !== "LEFT" && byKind !== "RIGHT") return byKind; if (this.peek().kind === "IDENT" /* IDENT */) { const name = this.peek().value.toUpperCase(); if (PARSER_IDENT_SCALAR_FUNCTIONS.includes(name)) { if (this.peekAt(1).kind === "(" /* LPAREN */) { return name; } } } return null; } parseStringFuncExpr() { const tokenKind = this.peek().kind; const func = this.tryStringFuncName(); this.advance(); this.expect("(" /* LPAREN */); if (tokenKind === "CAST" /* CAST */) { const valueArg = this.parseStringFuncArg(); this.expect("AS" /* AS */); const typeArg = this.parseCastType(); this.expect(")" /* RPAREN */); return { type: "STRING_FUNC", func: "CAST", args: [valueArg, typeArg] }; } if (tokenKind === "CONVERT" /* CONVERT */) { const valueArg = this.parseStringFuncArg(); this.expect("," /* COMMA */); const typeArg = this.parseCastType(); this.expect(")" /* RPAREN */); return { type: "STRING_FUNC", func: "CAST", args: [valueArg, typeArg] }; } const args = []; if (this.peek().kind !== ")" /* RPAREN */) { do { args.push(this.parseStringFuncArg()); } while (this.consume("," /* COMMA */)); } this.expect(")" /* RPAREN */); return { type: "STRING_FUNC", func, args }; } /** * CAST / CONVERT のキャスト先型を解析する。 * TEXT / VARCHAR / CHAR / STRING → "TEXT" * NUMBER / INT / INTEGER / NUMERIC / DECIMAL / FLOAT / DOUBLE → "NUMBER" * `SIZE(n)` 指定(VARCHAR(255) 等)はカッコを無視して型名だけ読む。 */ parseCastType() { const tok = this.peek(); let typeName; if (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) { this.advance(); typeName = tok.value.toUpperCase(); } else { throw new ParseError( "\u30AD\u30E3\u30B9\u30C8\u5148\u306E\u578B\u540D\uFF08TEXT, NUMBER, INT \u306A\u3069\uFF09\u304C\u5FC5\u8981\u3067\u3059", tok ); } if (this.peek().kind === "(" /* LPAREN */) { this.advance(); this.parseUnsignedInt(); this.expect(")" /* RPAREN */); } const normalized = normalizeCastType(typeName); if (normalized === null) { throw new ParseError( `\u4E0D\u660E\u306A\u30AD\u30E3\u30B9\u30C8\u578B\u300C${typeName}\u300D\u3002TEXT \u307E\u305F\u306F NUMBER \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`, tok ); } return { type: "STRING", value: normalized }; } /** 文字列関数の引数: ScalarValueExpr / 集計算術式 */ parseStringFuncArg() { if (this.scalarAllowsAggregateArgs) { const startPos = this.pos; try { const left = this.parseAggPrimary(); const expr = this.continueAggArith(left); if (this.hasAggregateOperand(expr)) return expr; } catch { } this.pos = startPos; } return this.parseScalarAddSubConcat(this.scalarAllowsCase); } hasAggregateOperand(node) { if (node.type === "AGG_REF") return true; if (node.type === "AGG_ARITH") { return this.hasAggregateOperand(node.left) || this.hasAggregateOperand(node.right); } return false; } tryAggregateFunc() { return PARSER_AGGREGATE_FUNCTION_TOKEN_MAP[this.peek().kind] ?? null; } /** 集計関数参照を読む。SELECT 列の alias は呼び出し側で式全体の後に処理する。 */ parseAggregateRef(func) { this.advance(); this.expect("(" /* LPAREN */); const distinct = this.consume("DISTINCT" /* DISTINCT */); const distinctToken = distinct ? this.prev() : null; if (func === "MODE" && distinctToken) { throw new ParseError("MODE \u3067\u306F DISTINCT \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", distinctToken); } let arg; if (this.consume("*" /* STAR */)) { if (!aggregateAcceptsWildcard(func)) { throw new ParseError(`${func}(*) \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u30D5\u30A3\u30FC\u30EB\u30C9\u307E\u305F\u306F\u5F0F\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`, this.prev()); } arg = { type: "WILDCARD" }; } else { arg = this.parseAggregateArgExpr(); } let separator; if (this.isSoftKeyword("SEPARATOR")) { const separatorToken = this.advance(); if (func !== "GROUP_CONCAT") { throw new ParseError("SEPARATOR \u306F GROUP_CONCAT \u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059", separatorToken); } separator = this.expect("STRING" /* STRING */, "SEPARATOR \u306E\u5F8C\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059").value; } this.expect(")" /* RPAREN */); return { type: "AGG_REF", func, distinct, arg, ...separator !== void 0 ? { separator } : {} }; } isAggregateArgEnd() { return this.peek().kind === ")" /* RPAREN */ || this.isSoftKeyword("SEPARATOR"); } /** 旧算術 AST を優先し、新規形だけ ScalarValueExpr として読む。 */ parseAggregateArgExpr() { const start = this.pos; try { const legacy = this.parseArithAddSub(); if (this.isAggregateArgEnd()) return legacy; } catch { } this.pos = start; this.insideAggregateArg++; try { let expr; try { expr = this.parseScalarValueExpr({ allowCase: true, allowAggregateArgs: false }); } catch (error51) { if (error51 instanceof ParseError) { if (error51.message.includes("\u6BD4\u8F03\u30FB\u8FF0\u8A9E")) { throw new ParseError( "\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u306B\u6BD4\u8F03\u30FB\u8FF0\u8A9E\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002CASE \u3067\u5024\u3092\u660E\u793A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u4F8B: SUM(CASE WHEN amount > 0 THEN 1 ELSE 0 END)", error51.token ); } if (error51.message.includes("\u96C6\u7D04\u95A2\u6570")) { throw new ParseError("\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u5185\u306B\u96C6\u8A08\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", error51.token); } } throw error51; } if (!this.isAggregateArgEnd()) { throw new ParseError( "\u3053\u306E\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u5F62\u5F0F\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002CASE \u3067\u5024\u3092\u660E\u793A\u3059\u308B\u304B\u3001CTE \u3067\u5F0F\u3092\u5217\u306B\u3057\u3066\u304B\u3089\u96C6\u8A08\u3057\u3066\u304F\u3060\u3055\u3044\u3002", this.peek() ); } this.assertNoNestedAggregate(expr); return expr; } finally { this.insideAggregateArg--; } } assertNoNestedAggregate(expr) { const visit = (value) => { if (value === null || typeof value !== "object") return; const node = value; if (node.type === "AGG_REF" || node.type === "AGG_ARITH") { throw new ParseError("\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u5185\u306B\u96C6\u8A08\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } for (const child of Object.values(node)) visit(child); }; visit(expr); } // ---------------------------------------------------------- // FROM / JOIN // ---------------------------------------------------------- parseTableRef() { const nameTok = this.peek(); const name = this.parseTableName(); if (nameTok.kind === "IDENT" /* IDENT */ && name.startsWith("#")) { this.tempTableRefs.push(this.prev()); const alias2 = this.consume("AS" /* AS */) ? this.parseTableAliasName() : this.tryParseImplicitAlias(); return { appId: 0, alias: alias2, cteName: name }; } if (this.cteNames.has(name)) { const alias2 = this.consume("AS" /* AS */) ? this.parseTableAliasName() : this.tryParseImplicitAlias(); return { appId: 0, alias: alias2, cteName: name }; } const { appId, subtableCode } = extractTableRef(name, this.prev()); if (subtableCode) { const alias2 = this.consume("AS" /* AS */) ? this.parseTableAliasName() : this.tryParseImplicitAlias(); return { appId, alias: alias2, cteName: null, subtableCode }; } const implicit = this.tryParseImplicitAlias(); const alias = this.consume("AS" /* AS */) ? this.parseTableAliasName() : implicit ?? name; return { appId, alias, cteName: null }; } // テーブル alias 名を読む(IDENT / BIDENT)。alias 位置の # は BIDENT でも拒否 parseTableAliasName() { const tok = this.peek(); if ((tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) && tok.value.startsWith("#")) { throw new ParseError("\u30A8\u30A4\u30EA\u30A2\u30B9\u540D\u306B # \u3067\u59CB\u307E\u308B\u540D\u524D\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } return this.parseIdentifier(); } tryParseImplicitAlias() { const k = this.peek().kind; if (k === "IDENT" /* IDENT */ || k === "BIDENT" /* BIDENT */) { if (k === "IDENT" /* IDENT */ && this.peek().value.toUpperCase() === "VALIDATE" && this.peekAt(1).kind === "IDENT" /* IDENT */ && this.peekAt(1).value.toUpperCase() === "ONLY") return null; if (k === "IDENT" /* IDENT */ && this.peek().value.toUpperCase() === "CHECK" && this.peekAt(1).kind === "WHEN" /* WHEN */) return null; return this.parseTableAliasName(); } return null; } parseJoins() { const joins = []; while (true) { const joinType = this.tryJoinType(); if (joinType === null) break; const table = this.parseTableRef(); this.expect("ON" /* ON */); const on = this.parseJoinCondition(); joins.push({ type: joinType, table, on }); } return joins; } tryJoinType() { if (this.consume("INNER" /* INNER */)) { this.expect("JOIN" /* JOIN */); return "INNER"; } if (this.consume("LEFT" /* LEFT */)) { this.expect("JOIN" /* JOIN */); return "LEFT"; } if (this.consume("RIGHT" /* RIGHT */)) { this.expect("JOIN" /* JOIN */); return "RIGHT"; } if (this.consume("JOIN" /* JOIN */)) { return "INNER"; } return null; } // ON a.field = b.field parseJoinCondition() { const left = this.parseQualifiedIdent(); this.expect("=" /* EQ */); const right = this.parseQualifiedIdent(); return { left, right }; } // alias.field または field parseQualifiedIdent() { const first = this.parseIdentifier(); if (this.consume("." /* DOT */)) { if (this.peek().kind === "*" /* STAR */) { throw new ParseError("\u3053\u3053\u3067\u306F * \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093", this.peek()); } const field = this.parseIdentifier(); return { tableAlias: first, field }; } return { tableAlias: null, field: first }; } // ---------------------------------------------------------- // WHERE 式(再帰下降・優先順位付き) // ---------------------------------------------------------- parseWhereExpr() { return this.parseOrExpr(); } // OR(最低優先度) parseOrExpr() { let left = this.parseAndExpr(); while (this.consume("OR" /* OR */)) { const right = this.parseAndExpr(); left = { type: "LOGICAL", op: "OR", left, right }; } return left; } // AND parseAndExpr() { let left = this.parseNotExpr(); while (this.consume("AND" /* AND */)) { const right = this.parseNotExpr(); left = { type: "LOGICAL", op: "AND", left, right }; } return left; } // NOT / EXISTS / NOT EXISTS parseNotExpr() { if (this.consume("EXISTS" /* EXISTS */)) { this.expect("(" /* LPAREN */); const query = this.parseSelect(); this.expect(")" /* RPAREN */); return { type: "EXISTS", not: false, query }; } if (this.consume("NOT" /* NOT */)) { if (this.consume("EXISTS" /* EXISTS */)) { this.expect("(" /* LPAREN */); const query = this.parseSelect(); this.expect(")" /* RPAREN */); return { type: "EXISTS", not: true, query }; } const expr = this.parseNotExpr(); return { type: "NOT", expr }; } return this.parseCompareExpr(); } /** * 現在位置が LPAREN のとき、その括弧が算術式の括弧かどうかを判定する。 * 対応する RPAREN の直後のトークンが算術演算子なら算術括弧、そうでなければ GROUP。 * 例: (単価 + 送料) * 数量 → true * (ステータス = '完了' OR ...) → false */ isArithParen() { let depth = 0; let i = this.pos; while (i < this.tokens.length) { const k = this.tokens[i].kind; if (k === "(" /* LPAREN */) depth++; else if (k === ")" /* RPAREN */) { depth--; if (depth === 0) { const next = this.tokens[i + 1]?.kind; return next === "*" /* STAR */ || next === "/" /* SLASH */ || next === "+" /* PLUS */ || next === "-" /* MINUS */; } } i++; } return false; } // 比較演算子: =, !=, <>, >, <, >=, <=, LIKE, KLIKE, IN, IS NULL parseCompareExpr() { if (this.peek().kind === "(" /* LPAREN */ && !this.isArithParen()) { this.advance(); const expr = this.parseWhereExpr(); this.expect(")" /* RPAREN */); return { type: "GROUP", expr }; } const field = this.parseFieldValue(); if (this.consume("IS" /* IS */)) { const not = this.consume("NOT" /* NOT */); this.expect("NULL" /* NULL */); return { type: "NULL_CHECK", field, not }; } if (this.consume("BETWEEN" /* BETWEEN */)) { const low = this.parseSqlValue(); this.expect("AND" /* AND */); const high = this.parseSqlValue(); return { type: "LOGICAL", op: "AND", left: { type: "BINARY", op: ">=", left: field, right: low }, right: { type: "BINARY", op: "<=", left: field, right: high } }; } if (this.consume("NOT" /* NOT */)) { if (this.consume("IN" /* IN */)) { const right2 = this.parseInRight(); return { type: "BINARY", op: "NOT_IN", left: field, right: right2 }; } if (this.consume("LIKE" /* LIKE */)) { const pattern = this.parseSqlValue(); return { type: "BINARY", op: "NOT_LIKE", left: field, right: pattern }; } if (this.consume("KLIKE" /* KLIKE */)) { const pattern = this.parseKlikePattern(); return { type: "BINARY", op: "NOT_KLIKE", left: field, right: pattern }; } throw new ParseError( "NOT \u306E\u5F8C\u306B\u306F IN\u3001LIKE\u3001KLIKE \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981\u3067\u3059", this.peek() ); } if (this.consume("IN" /* IN */)) { const right2 = this.parseInRight(); return { type: "BINARY", op: "IN", left: field, right: right2 }; } if (this.consume("KLIKE" /* KLIKE */)) { const pattern = this.parseKlikePattern(); return { type: "BINARY", op: "KLIKE", left: field, right: pattern }; } const op = this.parseCompareOp(); const right = this.parseSqlValue(); return { type: "BINARY", op, left: field, right }; } parseCompareOp() { const tok = this.advance(); switch (tok.kind) { case "=" /* EQ */: return "="; case "!=" /* NEQ */: return "!="; case "<>" /* LT_GT */: return "<>"; case ">" /* GT */: return ">"; case "<" /* LT */: return "<"; case ">=" /* GTE */: return ">="; case "<=" /* LTE */: return "<="; case "LIKE" /* LIKE */: return "LIKE"; default: throw new ParseError( "\u6BD4\u8F03\u6F14\u7B97\u5B50\uFF08=, !=, >, <, >=, <=, LIKE, KLIKE, IN, IS\uFF09\u304C\u5FC5\u8981\u3067\u3059", tok ); } } /** KLIKE / NOT KLIKE の右辺。kintone キーワードは文字列値だけを受け付ける。 */ parseKlikePattern() { const tok = this.peek(); if (tok.kind === "STRING" /* STRING */) { this.advance(); return { type: "STRING", value: tok.value }; } if (tok.kind === "VARIABLE" /* VARIABLE */) { this.advance(); return { type: "VARIABLE", name: tok.value.slice(1).toLowerCase() }; } throw new ParseError( "KLIKE / NOT KLIKE \u306E\u53F3\u8FBA\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u307E\u305F\u306F\u30D0\u30C3\u30C1\u5909\u6570\u304C\u5FC5\u8981\u3067\u3059", tok ); } // WHERE / HAVING の左辺 // - 文字列・数値関数: UPPER(f) / LENGTH(f) / ROUND(f, 2) ... // - 集計関数(HAVING のみ): COUNT(*) / SUM(f) ... // - 通常フィールド参照: [alias.]field parseFieldValue() { if (this.tryStringFuncName() !== null) { const expr = this.parseStringFuncExpr(); if (this.isArithOp(this.peek().kind)) { return { type: "ARITH_FIELD", expr: this.continueArith(expr) }; } return { type: "FUNC_FIELD", expr }; } const aggFunc = this.tryAggregateFunc(); if (aggFunc !== null) { if (this.insideAggregateArg > 0) { throw new ParseError("\u96C6\u8A08\u95A2\u6570\u306E\u5F15\u6570\u5185\u306B\u96C6\u8A08\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } const ref = this.parseAggregateRef(aggFunc); const syntheticName = aggregateSyntheticName(ref.func, ref.distinct, ref.arg); return { type: "FIELD", tableAlias: null, field: syntheticName }; } if (this.peek().kind === "CASE" /* CASE */) { const expr = this.parseCaseWhenExpr(); return { type: "CASE_FIELD", expr }; } if (this.peek().kind === "IF" /* IF */) { const expr = this.parseIfExpr(); return { type: "CASE_FIELD", expr }; } if (this.peek().kind === "(" /* LPAREN */) { this.advance(); const inner = this.parseArithAddSub(); this.expect(")" /* RPAREN */); const expr = this.continueArith(inner); return { type: "ARITH_FIELD", expr }; } if (this.peek().kind === "-" /* MINUS */) { return { type: "ARITH_FIELD", expr: this.parseArithAddSub() }; } const qi = this.parseQualifiedIdent(); if (this.isArithOp(this.peek().kind)) { const baseField = qi.tableAlias ? `${qi.tableAlias}.${qi.field}` : qi.field; const left = { type: "FIELD_REF", field: baseField }; return { type: "ARITH_FIELD", expr: this.continueArith(left) }; } return { type: "FIELD", tableAlias: qi.tableAlias, field: qi.field }; } // 右辺の値 parseSqlValue() { const tok = this.peek(); if (tok.kind === "VARIABLE" /* VARIABLE */) { this.advance(); return { type: "VARIABLE", name: tok.value.slice(1).toLowerCase() }; } if (tok.kind === "STRING" /* STRING */) { this.advance(); return { type: "STRING", value: tok.value }; } if (isContextualFunctionToken(tok.kind)) { this.advance(); this.expect("(" /* LPAREN */); this.expect(")" /* RPAREN */); return { type: "KINTONE_FUNC", name: PARSER_CONTEXTUAL_FUNCTION_TOKEN_MAP[tok.kind] }; } if (tok.kind === "CASE" /* CASE */) { const expr = this.parseCaseWhenExpr(); return { type: "CASE_VALUE", expr }; } if (tok.kind === "IF" /* IF */) { const expr = this.parseIfExpr(); return { type: "CASE_VALUE", expr }; } if (tok.kind === "(" /* LPAREN */ && this.peekAt(1).kind === "SELECT" /* SELECT */) { this.advance(); const query = this.parseSelect(); this.expect(")" /* RPAREN */); if (this.isArithOp(this.peek().kind)) { throw new ParseError( "\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306E\u5F8C\u306B\u7B97\u8853\u6F14\u7B97\u5B50\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u30B5\u30D6\u30AF\u30A8\u30EA\u5185\u3067\u8A08\u7B97\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u4F8B: (SELECT AVG(\u5408\u8A08\u8CBB\u7528)/2 FROM APP88)\uFF09", this.peek() ); } return { type: "SCALAR_SUBQUERY", query }; } if (tok.kind === "NUMBER" /* NUMBER */ || tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */ || tok.kind === "(" /* LPAREN */ || tok.kind === "-" /* MINUS */ || this.tryStringFuncName() !== null) { const expr = this.parseArithAddSub(); if (expr.type === "NUMBER") return expr; return { type: "ARITH_VALUE", expr }; } throw new ParseError( "\u5024\uFF08\u6587\u5B57\u5217\u30FB\u6570\u5024\u30FB\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u30FBTODAY()\u30FBNOW()\u30FBLOGINUSER()\uFF09\u304C\u5FC5\u8981\u3067\u3059", tok ); } // IN (...) — 値リストまたはサブクエリ parseInRight() { if (this.consume("(" /* LPAREN */)) { const right = this.parseInListOrSubquery(); this.expect(")" /* RPAREN */); return right; } const variable = this.expect( "VARIABLE" /* VARIABLE */, "IN / NOT IN \u306E\u5F8C\u306B\u306F (\u5024\u30EA\u30B9\u30C8\u307E\u305F\u306F SELECT) \u304B\u914D\u5217\u5909\u6570\u304C\u5FC5\u8981\u3067\u3059" ); return { type: "VARIABLE_IN_LIST", name: variable.value.slice(1).toLowerCase() }; } parseInListOrSubquery() { if (this.peek().kind === "SELECT" /* SELECT */) { const query = this.parseSelect(); const firstCol = query.columns[0]; const column = firstCol && firstCol.type === "FIELD" ? firstCol.alias ?? firstCol.field : null; return { type: "SUBQUERY_IN_LIST", query, column }; } return { type: "IN_LIST", values: this.parseInValues() }; } // IN リストの値 parseInValues() { const values = []; const invalidValueMessage = "IN \u30EA\u30B9\u30C8\u306B\u306F\u6587\u5B57\u5217\u3001\u6570\u5024\u3001\u307E\u305F\u306F\u30D0\u30C3\u30C1\u5909\u6570\u304C\u5FC5\u8981\u3067\u3059"; do { const tok = this.advance(); if (tok.kind === "STRING" /* STRING */) { values.push({ type: "STRING", value: tok.value }); } else if (tok.kind === "NUMBER" /* NUMBER */) { values.push(makeNumberLiteral(tok.value)); } else if (tok.kind === "-" /* MINUS */ || tok.kind === "+" /* PLUS */) { const number4 = this.peek(); if (number4.kind !== "NUMBER" /* NUMBER */) { throw new ParseError(invalidValueMessage, tok); } this.advance(); const sign = tok.kind === "-" /* MINUS */ ? "-" : "+"; values.push(makeNumberLiteral(`${sign}${number4.value}`)); } else if (tok.kind === "VARIABLE" /* VARIABLE */) { values.push({ type: "VARIABLE", name: tok.value.slice(1).toLowerCase() }); } else { throw new ParseError(invalidValueMessage, tok); } } while (this.consume("," /* COMMA */)); return values; } // ---------------------------------------------------------- // GROUP BY / ORDER BY // ---------------------------------------------------------- parseIdentList() { const idents = []; do { idents.push(this.parseIdentifier()); } while (this.consume("," /* COMMA */)); return idents; } parseGroupByKeys() { const keys = []; do { keys.push(this.parseGroupByKey()); } while (this.consume("," /* COMMA */)); return keys; } /** * GROUP BY のキーを解析する。ORDER BY と同じ文法(方向指定なし)。 * 関数: SUBSTRING(作成日時, 1, 7) / ROUND(金額, -4) * 算術式(( や数値): (単価 + 税額) * 数量 * フィールド + 算術: 金額 * 1.1 * フィールド名: 部署 / 担当者 */ parseGroupByKey() { if (this.tryStringFuncName() !== null) { const funcExpr = this.parseStringFuncExpr(); if (this.isArithOp(this.peek().kind)) { return { type: "ARITH_KEY", expr: this.continueArith(funcExpr) }; } return { type: "FUNC_KEY", expr: funcExpr }; } if (this.peek().kind === "(" /* LPAREN */ || this.peek().kind === "NUMBER" /* NUMBER */) { return { type: "ARITH_KEY", expr: this.parseArithAddSub() }; } const name = this.parseFieldPath(); if (this.isArithOp(this.peek().kind)) { const left = { type: "FIELD_REF", field: name }; return { type: "ARITH_KEY", expr: this.continueArith(left) }; } return { type: "FIELD_NAME", name }; } parseOrderBy() { const items = []; do { const key = this.parseOrderByKey(); let direction = "ASC"; if (this.consume("DESC" /* DESC */)) direction = "DESC"; else this.consume("ASC" /* ASC */); items.push({ key, direction }); } while (this.consume("," /* COMMA */)); return items; } /** * ORDER BY のソートキーを解析する。 * 関数: UPPER(名前) / LENGTH(名前) / ROUND(金額, -3) * 算術式(( や数値): (金額 + 税額) / 1000 * フィールド + 算術: 金額 * 1.1 * フィールド名/alias: 名前 / total */ parseOrderByKey() { if (this.tryStringFuncName() !== null) { const funcExpr = this.parseStringFuncExpr(); if (this.isArithOp(this.peek().kind)) { return { type: "ARITH_KEY", expr: this.continueArith(funcExpr) }; } return { type: "FUNC_KEY", expr: funcExpr }; } if (this.peek().kind === "(" /* LPAREN */ || this.peek().kind === "NUMBER" /* NUMBER */) { return { type: "ARITH_KEY", expr: this.parseArithAddSub() }; } const name = this.parseFieldPath(); if (this.isArithOp(this.peek().kind)) { const left = { type: "FIELD_REF", field: name }; return { type: "ARITH_KEY", expr: this.continueArith(left) }; } return { type: "FIELD_NAME", name }; } // ---------------------------------------------------------- // INSERT // ---------------------------------------------------------- parseInsert() { this.expect("INSERT" /* INSERT */); this.expect("INTO" /* INTO */); this.rejectTempTableDml(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); this.expect("(" /* LPAREN */); const fields = this.parseIdentList(); this.expect(")" /* RPAREN */); if (this.peek().kind === "SELECT" /* SELECT */) { const select = this.parseSelect(); if (this.isApplyBlockStart() || this.prev().kind === "IDENT" /* IDENT */ && this.prev().value.toUpperCase() === "APPLY" && (this.peek().kind === "IDENT" /* IDENT */ || this.peek().kind === "BIDENT" /* BIDENT */) && this.peekAt(1).kind === "(" /* LPAREN */) { throw new ParseError("INSERT INTO ... SELECT \u306F APPLY \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev()); } if (subtableCode) { throw new ParseError("INSERT INTO ... SELECT \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u3067\u306F\u672A\u5BFE\u5FDC\u3067\u3059", this.prev()); } const checkGroups2 = this.parseCheckGroups(); const validation2 = this.parseDmlControlSuffix(); return { type: "INSERT_SELECT", appId, fields, select, ...checkGroups2, ...validation2 }; } this.expect("VALUES" /* VALUES */); const values = []; do { this.expect("(" /* LPAREN */); const row = this.parseInsertRow(fields.length); this.expect(")" /* RPAREN */); values.push(row); } while (this.consume("," /* COMMA */)); const applyBlocks = []; while (this.isApplyBlockStart()) applyBlocks.push(this.parseApplyBlock()); if (this.isSoftKeyword("APPLY") && this.peekAt(1).kind === "IDENT" /* IDENT */ && this.peekAt(1).value.toUpperCase() === "SUBTABLE") { throw new ParseError( "APPLY SUBTABLE noun is not supported; use APPLY (...)", this.peek() ); } if (applyBlocks.length > 0 && this.isSoftKeyword("CHECK")) { throw new ParseError("APPLY \u30D6\u30ED\u30C3\u30AF\u306E\u5F8C\u306B CHECK \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093", this.peek()); } if (applyBlocks.length > 0 && (this.peek().kind === "ON" /* ON */ || this.isSoftKeyword("REJECT"))) { throw new ParseError("ON ERROR SKIP / REJECT LIMIT \u306F APPLY \u3068\u4F75\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } const checkGroups = this.parseCheckGroups(); const validation = this.parseDmlControlSuffix(); if (this.isSoftKeyword("APPLY")) { throw new ParseError("APPLY \u306F CHECK / VALIDATE ONLY \u3088\u308A\u524D\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", this.peek()); } if (subtableCode && checkGroups.checkGroups) { throw new ParseError("CHECK \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB INSERT \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev()); } if (subtableCode && (validation.validateOnly || validation.onErrorSkip)) { throw new ParseError("VALIDATE ONLY / ON ERROR SKIP \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB INSERT \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev()); } const apply = applyBlocks.length > 0 ? { applyBlocks } : {}; return subtableCode ? { type: "INSERT", appId, subtableCode, fields, values, ...apply, ...checkGroups, ...validation } : { type: "INSERT", appId, fields, values, ...apply, ...checkGroups, ...validation }; } parseUpsert() { this.expect("UPSERT" /* UPSERT */); this.expect("INTO" /* INTO */); this.rejectTempTableDml(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); if (subtableCode) { throw new ParseError("UPSERT \u306F\u307E\u3060\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev()); } this.expect("(" /* LPAREN */); const fields = this.parseIdentList(); this.expect(")" /* RPAREN */); if (this.peek().kind === "SELECT" /* SELECT */) { const select = this.parseSelect(); const keyFields2 = this.parseOnDuplicate(); if (this.isUpsertApplyBranchStart() || this.isApplyBlockStart()) { throw new ParseError("UPSERT INTO ... SELECT \u306F ON INSERT / ON UPDATE APPLY \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.peek()); } const checkGroups2 = this.parseCheckGroups(); const validation2 = this.parseDmlControlSuffix(); if (this.isUpsertApplyBranchStart() || this.isApplyBlockStart()) { throw new ParseError("UPSERT INTO ... SELECT \u306F ON INSERT / ON UPDATE APPLY \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.peek()); } return { type: "UPSERT_SELECT", appId, fields, select, keyFields: keyFields2, ...checkGroups2, ...validation2 }; } this.expect("VALUES" /* VALUES */); const values = []; do { this.expect("(" /* LPAREN */); values.push(this.parseInsertRow(fields.length)); this.expect(")" /* RPAREN */); } while (this.consume("," /* COMMA */)); const keyFields = this.parseOnDuplicate(); const applyBranches = this.parseUpsertApplyBranches(); const hasApplyBranches = applyBranches.onInsertApplyBlocks !== void 0 || applyBranches.onUpdateApplyBlocks !== void 0; if (hasApplyBranches && this.isSoftKeyword("CHECK")) { throw new ParseError("UPSERT \u306E\u5206\u5C90 APPLY \u306F CHECK \u3068\u4F75\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } if (hasApplyBranches && (this.peek().kind === "ON" /* ON */ || this.isSoftKeyword("REJECT"))) { throw new ParseError("UPSERT \u306E\u5206\u5C90 APPLY \u306F ON ERROR SKIP / REJECT LIMIT \u3068\u4F75\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } const checkGroups = this.parseCheckGroups(); const validation = this.parseDmlControlSuffix(); if (this.isUpsertApplyBranchStart() || this.isApplyBlockStart()) { throw new ParseError("ON INSERT / ON UPDATE APPLY \u306F CHECK / VALIDATE ONLY \u3088\u308A\u524D\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", this.peek()); } return { type: "UPSERT", appId, fields, values, keyFields, ...applyBranches, ...checkGroups, ...validation }; } parseOnDuplicate() { this.expectKeyword("ON" /* ON */, "UPSERT \u306B\u306F ON DUPLICATE (\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9) \u304C\u5FC5\u8981\u3067\u3059"); if (!this.consume("DUPLICATE" /* DUPLICATE */)) { throw new ParseError("ON \u306E\u5F8C\u306B\u306F DUPLICATE \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } this.expect("(" /* LPAREN */); const keyFields = this.parseIdentList(); this.expect(")" /* RPAREN */); if (keyFields.length === 0) { throw new ParseError("ON DUPLICATE \u306B\u306F\u30AD\u30FC\u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u6700\u4F4E 1 \u3064\u5FC5\u8981\u3067\u3059", this.prev()); } return keyFields; } isUpsertApplyBranchStart() { return this.peek().kind === "ON" /* ON */ && (this.peekAt(1).kind === "INSERT" /* INSERT */ || this.peekAt(1).kind === "UPDATE" /* UPDATE */); } parseUpsertApplyBranches() { let onInsertApplyBlocks; let onUpdateApplyBlocks; while (this.isUpsertApplyBranchStart()) { this.advance(); const branch = this.advance(); const isInsert = branch.kind === "INSERT" /* INSERT */; if (isInsert && onInsertApplyBlocks || !isInsert && onUpdateApplyBlocks) { throw new ParseError(`ON ${isInsert ? "INSERT" : "UPDATE"} APPLY \u306F 1 \u56DE\u3060\u3051\u6307\u5B9A\u3067\u304D\u307E\u3059`, branch); } if (!this.isApplyBlockStart()) { throw new ParseError(`ON ${isInsert ? "INSERT" : "UPDATE"} \u306E\u5F8C\u306B\u306F APPLY \u30D6\u30ED\u30C3\u30AF\u304C\u5FC5\u8981\u3067\u3059`, this.peek()); } const blocks = []; while (this.isApplyBlockStart()) blocks.push(this.parseApplyBlock()); if (isInsert) onInsertApplyBlocks = blocks; else onUpdateApplyBlocks = blocks; } if (this.isApplyBlockStart()) { throw new ParseError("UPSERT \u306E APPLY \u306B\u306F ON INSERT \u307E\u305F\u306F ON UPDATE \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } return { ...onInsertApplyBlocks ? { onInsertApplyBlocks } : {}, ...onUpdateApplyBlocks ? { onUpdateApplyBlocks } : {} }; } /** 配列リテラル ['val1', 'val2'] を解析して ArrayLiteral を返す */ parseArrayLiteral() { this.expect("[" /* LBRACKET */); const elements = []; if (this.peek().kind !== "]" /* RBRACKET */) { do { const tok = this.expect("STRING" /* STRING */); elements.push({ type: "STRING", value: tok.value }); } while (this.consume("," /* COMMA */)); } this.expect("]" /* RBRACKET */); return { type: "ARRAY", elements }; } parseInsertRow(expectedLen) { const row = []; do { if (this.peek().kind === "[" /* LBRACKET */) { row.push(this.parseArrayLiteral()); } else if (this.peek().kind === "CASE" /* CASE */) { const expr = this.parseCaseWhenExpr(); row.push({ type: "CASE_VALUE", expr }); } else if (this.peek().kind === "IF" /* IF */) { const expr = this.parseIfExpr(); row.push({ type: "CASE_VALUE", expr }); } else if (this.peek().kind === "-" /* MINUS */ || this.peek().kind === "+" /* PLUS */) { const sign = this.advance(); const number4 = this.expect("NUMBER" /* NUMBER */, "INSERT \u306E\u5358\u9805\u7B26\u53F7\u306E\u76F4\u5F8C\u306B\u306F\u6570\u5024\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059"); row.push(makeNumberLiteral(`${sign.kind === "-" /* MINUS */ ? "-" : "+"}${number4.value}`)); } else { const tok = this.advance(); if (tok.kind === "STRING" /* STRING */) { row.push({ type: "STRING", value: tok.value }); } else if (tok.kind === "NUMBER" /* NUMBER */) { row.push(makeNumberLiteral(tok.value)); } else { throw new ParseError("INSERT \u306E\u5024\u306B\u306F\u6587\u5B57\u5217\u30FB\u6570\u5024\u30FB\u914D\u5217\u30EA\u30C6\u30E9\u30EB\u30FBCASE WHEN \u304C\u5FC5\u8981\u3067\u3059", tok); } } } while (this.consume("," /* COMMA */)); if (row.length !== expectedLen) { throw new ParseError( `\u30AB\u30E9\u30E0\u6570\uFF08${expectedLen}\uFF09\u3068\u5024\u306E\u6570\uFF08${row.length}\uFF09\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093`, this.prev() ); } return row; } // ---------------------------------------------------------- // UPDATE // ---------------------------------------------------------- parseUpdate() { this.expect("UPDATE" /* UPDATE */); this.rejectTempTableDml(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); this.expect("SET" /* SET */); const assignments = this.parseAssignments(); if (subtableCode && assignments.some((a) => a.value.type === "STRING_FUNC")) { throw new ParseError( "\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE SET \u3067\u306F\u6587\u5B57\u5217\u95A2\u6570\u3092\u76F4\u63A5\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", this.prev() ); } let from = null; if (this.consume("FROM" /* FROM */)) { const table = this.parseTableRef(); if (table.subtableCode) { throw new ParseError("UPDATE ... FROM \u306E\u30BD\u30FC\u30B9\u306B\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093", this.prev()); } if (table.cteName !== null && !table.cteName.startsWith("#")) { throw new ParseError("UPDATE ... FROM \u306E\u30BD\u30FC\u30B9\u306F #temp \u307E\u305F\u306F APP \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08CTE \u306F\u975E\u5BFE\u5FDC\uFF09", this.prev()); } if (!table.alias) { throw new ParseError("UPDATE ... FROM \u306E\u30BD\u30FC\u30B9\u306B\u306F\u30A8\u30A4\u30EA\u30A2\u30B9\u304C\u5FC5\u8981\u3067\u3059", this.prev()); } if (table.alias.toLowerCase() === `app${appId}`.toLowerCase()) { throw new ParseError(`UPDATE ... FROM \u306E\u30BD\u30FC\u30B9 alias \u306F\u66F4\u65B0\u5148 APP${appId} \u3068\u540C\u540D\u306B\u3067\u304D\u307E\u305B\u3093`, this.prev()); } from = { appId: table.appId, cteName: table.cteName, alias: table.alias, targetJoinField: "", joinKeyField: "", targetFilter: null }; } const whereTok = this.peek(); if (!this.consume("WHERE" /* WHERE */)) { throw new ParseError( "UPDATE \u6587\u306B\u306F WHERE \u53E5\u304C\u5FC5\u8981\u3067\u3059\uFF08\u5168\u4EF6\u66F4\u65B0\u3092\u9632\u3050\u305F\u3081\uFF09", whereTok ); } const where = this.parseWhereExpr(); const applyBlocks = []; while (this.isApplyBlockStart()) applyBlocks.push(this.parseApplyBlock()); if (this.isSoftKeyword("APPLY") && this.peekAt(1).kind === "IDENT" /* IDENT */ && this.peekAt(1).value.toUpperCase() === "SUBTABLE") { throw new ParseError( "APPLY SUBTABLE noun is not supported; use APPLY (...)", this.peek() ); } if (applyBlocks.length > 0 && this.peek().kind === "WHERE" /* WHERE */) { throw new ParseError("\u89AA WHERE \u306F APPLY \u30D6\u30ED\u30C3\u30AF\u3088\u308A\u524D\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", this.peek()); } if (from !== null) { if (subtableCode) { throw new ParseError("\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE ... FROM \u306F\u30B5\u30DD\u30FC\u30C8\u3057\u3066\u3044\u307E\u305B\u3093", whereTok); } this.validateUpdateFromAssignments(assignments, from.alias, whereTok); const decomposed = this.decomposeUpdateFromWhere(where, appId, from.alias, whereTok); from.targetJoinField = decomposed.targetJoinField; from.joinKeyField = decomposed.joinKeyField; from.targetFilter = decomposed.targetFilter; } else if (assignments.some((a) => a.value.type === "SOURCE_FIELD")) { throw new ParseError( "SET \u306E\u5024\u306B\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3092\u5358\u72EC\u3067\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093", whereTok ); } else if (assignments.some( (a) => a.value.type === "STRING_FUNC" && this.nodeContainsAnyQualifier(a.value) )) { throw new ParseError( "UPDATE SET \u306E\u6587\u5B57\u5217\u95A2\u6570\u3067\u306F\u66F4\u65B0\u5148\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u4FEE\u98FE\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044", whereTok ); } if (applyBlocks.length > 0 && this.isSoftKeyword("CHECK")) { throw new ParseError("APPLY \u30D6\u30ED\u30C3\u30AF\u306E\u5F8C\u306B CHECK \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093", this.peek()); } if (applyBlocks.length > 0 && (this.peek().kind === "ON" /* ON */ || this.isSoftKeyword("REJECT"))) { throw new ParseError("ON ERROR SKIP / REJECT LIMIT \u306F APPLY \u3068\u4F75\u7528\u3067\u304D\u307E\u305B\u3093", this.peek()); } const checkGroups = this.parseCheckGroups(); const validation = this.parseDmlControlSuffix(); if (this.isSoftKeyword("APPLY")) { throw new ParseError("APPLY \u306F VALIDATE ONLY \u3088\u308A\u524D\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", this.peek()); } if (subtableCode && checkGroups.checkGroups) { throw new ParseError("CHECK \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev()); } if (subtableCode && (validation.validateOnly || validation.onErrorSkip)) { throw new ParseError("VALIDATE ONLY / ON ERROR SKIP \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093", this.prev()); } const apply = applyBlocks.length > 0 ? { applyBlocks } : {}; if (from !== null) return { type: "UPDATE", appId, assignments, where, from, ...apply, ...checkGroups, ...validation }; return subtableCode ? { type: "UPDATE", appId, subtableCode, assignments, where, ...apply, ...checkGroups, ...validation } : { type: "UPDATE", appId, assignments, where, ...apply, ...checkGroups, ...validation }; } isApplyBlockStart() { return this.isSoftKeyword("APPLY") && (this.peekAt(1).kind === "IDENT" /* IDENT */ || this.peekAt(1).kind === "BIDENT" /* BIDENT */) && this.peekAt(2).kind === "(" /* LPAREN */; } parseApplyBlock() { this.advance(); const field = this.parseIdentifier(); this.expect("(" /* LPAREN */); if (this.peek().kind === ")" /* RPAREN */ || this.peek().kind === ";" /* SEMICOLON */) { throw new ParseError("APPLY \u30D6\u30ED\u30C3\u30AF\u306B\u306F\u64CD\u4F5C\u304C\u6700\u4F4E 1 \u3064\u5FC5\u8981\u3067\u3059", this.peek()); } const operations = []; while (true) { operations.push(this.parseApplyOperation()); if (!this.consume(";" /* SEMICOLON */)) break; if (this.peek().kind === ")" /* RPAREN */) break; if (this.peek().kind === ";" /* SEMICOLON */) { throw new ParseError("APPLY \u30D6\u30ED\u30C3\u30AF\u306B\u7A7A\u306E\u64CD\u4F5C\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093", this.peek()); } } this.expect(")" /* RPAREN */, "APPLY \u30D6\u30ED\u30C3\u30AF\u306E\u672B\u5C3E\u306B\u306F ) \u304C\u5FC5\u8981\u3067\u3059"); const hasSubtableOperation = operations.some( (operation) => operation.kind === "PATCH" || operation.kind === "APPEND" || operation.kind === "REMOVE" ); const hasMultiValueOperation = operations.some( (operation) => operation.kind === "ADD" || operation.kind === "REMOVE_VALUE" ); if (hasSubtableOperation && hasMultiValueOperation) { throw new ParseError("1 \u3064\u306E APPLY \u30D6\u30ED\u30C3\u30AF\u306B\u884C\u64CD\u4F5C\u3068\u591A\u5024\u64CD\u4F5C\u306F\u6DF7\u5728\u3067\u304D\u307E\u305B\u3093", this.prev()); } return hasMultiValueOperation ? { field, targetKind: "MULTI_VALUE", operations } : { field, targetKind: "SUBTABLE", operations }; } parseApplyOperation() { if (this.isSoftKeyword("ADD")) { this.advance(); const value = this.expect("STRING" /* STRING */, "ADD \u306E\u5F8C\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u304C\u5FC5\u8981\u3067\u3059").value; return { kind: "ADD", value }; } if (this.isSoftKeyword("PATCH")) { this.advance(); this.expect("SET" /* SET */, "PATCH \u306E\u5F8C\u306B\u306F SET \u304C\u5FC5\u8981\u3067\u3059"); const assignments = this.parseAssignments(); const selector = this.parseApplyRowSelector(); const expectRows = this.parseExpectRowsGuard(); return { kind: "PATCH", assignments, selector, ...expectRows ? { expectRows } : {} }; } if (this.isSoftKeyword("APPEND")) { this.advance(); this.expect("(" /* LPAREN */, "APPEND \u306E\u5F8C\u306B\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u4E00\u89A7\u304C\u5FC5\u8981\u3067\u3059"); if (this.peek().kind === ")" /* RPAREN */) { throw new ParseError("APPEND \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u4E00\u89A7\u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093", this.peek()); } const fields = []; do fields.push(this.parseIdentifier()); while (this.consume("," /* COMMA */)); this.expect(")" /* RPAREN */); this.expect("VALUES" /* VALUES */, "APPEND \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u4E00\u89A7\u306E\u5F8C\u306B\u306F VALUES \u304C\u5FC5\u8981\u3067\u3059"); const values = []; do { this.expect("(" /* LPAREN */, "APPEND VALUES \u306E\u5404\u884C\u306F ( \u3067\u59CB\u3081\u3066\u304F\u3060\u3055\u3044"); values.push(this.parseInsertRow(fields.length)); this.expect(")" /* RPAREN */); } while (this.consume("," /* COMMA */)); return { kind: "APPEND", fields, values }; } if (this.isSoftKeyword("REMOVE")) { this.advance(); if (this.peek().kind === "STRING" /* STRING */) { return { kind: "REMOVE_VALUE", value: this.advance().value }; } const selector = this.parseApplyRowSelector(); const expectRows = this.parseExpectRowsGuard(); return { kind: "REMOVE", selector, ...expectRows ? { expectRows } : {} }; } throw new ParseError("APPLY \u306E\u64CD\u4F5C\u306B\u306F PATCH / APPEND / REMOVE / ADD \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } parseApplyRowSelector() { if (this.consume("WHERE" /* WHERE */)) return { kind: "WHERE", where: this.parseWhereExpr() }; if (this.consume("ALL" /* ALL */)) { if (!this.isSoftKeyword("ROWS")) throw new ParseError("ALL \u306E\u5F8C\u306B\u306F ROWS \u304C\u5FC5\u8981\u3067\u3059", this.peek()); this.advance(); return { kind: "ALL_ROWS" }; } throw new ParseError("PATCH / REMOVE \u306B\u306F WHERE \u307E\u305F\u306F ALL ROWS \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } parseExpectRowsGuard() { if (!this.isSoftKeyword("EXPECT")) return void 0; this.advance(); if (!this.isSoftKeyword("ROWS")) throw new ParseError("EXPECT \u306E\u5F8C\u306B\u306F ROWS \u304C\u5FC5\u8981\u3067\u3059", this.peek()); this.advance(); if (this.consume("BETWEEN" /* BETWEEN */)) { const min = this.parseExpectRowsCount(); this.expect("AND" /* AND */, "EXPECT ROWS BETWEEN \u306E\u4E0B\u9650\u3068\u4E0A\u9650\u306F AND \u3067\u533A\u5207\u3063\u3066\u304F\u3060\u3055\u3044"); const max = this.parseExpectRowsCount(); if (min > max) throw new ParseError("EXPECT ROWS BETWEEN \u306E\u4E0B\u9650\u306F\u4E0A\u9650\u4EE5\u4E0B\u306B\u3057\u3066\u304F\u3060\u3055\u3044", this.peek()); return { kind: "BETWEEN", min, max }; } if (this.isSoftKeyword("AT")) { this.advance(); if (this.peek().value.toUpperCase() === "LEAST") { this.advance(); return { kind: "AT_LEAST", count: this.parseExpectRowsCount() }; } if (this.isSoftKeyword("MOST")) { this.advance(); return { kind: "AT_MOST", count: this.parseExpectRowsCount() }; } throw new ParseError("EXPECT ROWS AT \u306E\u5F8C\u306B\u306F LEAST \u307E\u305F\u306F MOST \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } return { kind: "EXACT", count: this.parseExpectRowsCount() }; } parseExpectRowsCount() { const tok = this.expect("NUMBER" /* NUMBER */, "EXPECT ROWS \u306B\u306F 0 \u4EE5\u4E0A\u306E\u6574\u6570\u304C\u5FC5\u8981\u3067\u3059"); if (!/^\d+$/.test(tok.value) || !Number.isSafeInteger(Number(tok.value))) { throw new ParseError("EXPECT ROWS \u306F 0 \u4EE5\u4E0A\u306E\u5B89\u5168\u306A\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", tok); } return Number(tok.value); } /** CHECK WHEN ... THEN ... blocks. CHECK is a soft keyword. */ parseCheckGroups() { const groups = []; while (this.isSoftKeyword("CHECK") && this.peekAt(1).kind === "WHEN" /* WHEN */) { const check2 = this.advance(); const rules = []; while (this.consume("WHEN" /* WHEN */)) { const condition = this.parseWhereExpr(); this.expect("THEN" /* THEN */, "CHECK WHEN \u306E\u6761\u4EF6\u306E\u5F8C\u306B\u306F THEN \u304C\u5FC5\u8981\u3067\u3059"); const message = this.parseScalarValueExpr({ allowCase: false }); rules.push({ condition, message }); } if (rules.length === 0) throw new ParseError("CHECK \u306E\u5F8C\u306B\u306F WHEN \u304C\u6700\u4F4E 1 \u3064\u5FC5\u8981\u3067\u3059", check2); groups.push({ rules }); } return groups.length > 0 ? { checkGroups: groups } : {}; } /** DML末尾の VALIDATE ONLY または ON ERROR SKIP。各語はsoft keyword。 */ parseDmlControlSuffix() { if (this.peek().kind === "ON" /* ON */) return this.parseOnErrorSkipSuffix(); if (this.isSoftKeyword("REJECT")) { throw new ParseError("REJECT LIMIT \u306B\u306F ON ERROR SKIP INTO \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } if (!this.isSoftKeyword("VALIDATE")) return {}; const validateTok = this.advance(); if (!this.isSoftKeyword("ONLY")) { throw new ParseError("VALIDATE \u306E\u5F8C\u306B\u306F ONLY \u304C\u5FC5\u8981\u3067\u3059", this.peek()); } this.advance(); let validationErrorTable = null; if (this.consume("INTO" /* INTO */)) { const tok = this.peek(); if (tok.kind !== "IDENT" /* IDENT */ || !tok.value.startsWith("#")) { throw new ParseError("VALIDATE ONLY INTO \u306B\u306F # \u3067\u59CB\u307E\u308B\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\u304C\u5FC5\u8981\u3067\u3059", tok); } validationErrorTable = this.parseTableName(); } if (this.peek().kind === "ON" /* ON */ || this.isSoftKeyword("REJECT")) { throw new ParseError("VALIDATE ONLY \u3068 ON ERROR / REJECT LIMIT \u306F\u4F75\u8A18\u3067\u304D\u307E\u305B\u3093", validateTok); } return { validateOnly: true, validationErrorTable }; } parseOnErrorSkipSuffix() { const onTok = this.advance(); if (!this.isSoftKeyword("ERROR")) throw new ParseError("ON \u306E\u5F8C\u306B\u306F ERROR \u304C\u5FC5\u8981\u3067\u3059", this.peek()); this.advance(); if (!this.isSoftKeyword("SKIP")) throw new ParseError("ON ERROR \u306E\u5F8C\u306B\u306F SKIP \u304C\u5FC5\u8981\u3067\u3059", this.peek()); this.advance(); this.expect("INTO" /* INTO */, "ON ERROR SKIP \u306B\u306F INTO #\u4E00\u6642\u30C6\u30FC\u30D6\u30EB \u304C\u5FC5\u8981\u3067\u3059"); const tableTok = this.peek(); if (tableTok.kind !== "IDENT" /* IDENT */ || !tableTok.value.startsWith("#")) { throw new ParseError("ON ERROR SKIP INTO \u306B\u306F # \u3067\u59CB\u307E\u308B\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\u304C\u5FC5\u8981\u3067\u3059", tableTok); } const errorTable = this.parseTableName(); let rejectLimit = null; if (this.isSoftKeyword("REJECT")) { this.advance(); this.expect("LIMIT" /* LIMIT */, "REJECT \u306E\u5F8C\u306B\u306F LIMIT \u304C\u5FC5\u8981\u3067\u3059"); const tok = this.expect("NUMBER" /* NUMBER */, "REJECT LIMIT \u306B\u306F 0 \u4EE5\u4E0A\u306E\u6574\u6570\u304C\u5FC5\u8981\u3067\u3059"); if (!/^\d+$/.test(tok.value)) throw new ParseError("REJECT LIMIT \u306F 0 \u4EE5\u4E0A\u306E\u5B89\u5168\u306A\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", tok); rejectLimit = Number(tok.value); if (!Number.isSafeInteger(rejectLimit)) throw new ParseError("REJECT LIMIT \u306F 0 \u4EE5\u4E0A\u306E\u5B89\u5168\u306A\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044", tok); } if (this.isSoftKeyword("REJECT") || this.isSoftKeyword("VALIDATE") || this.peek().kind === "ON" /* ON */) { throw new ParseError("ON ERROR SKIP \u306E\u53E5\u304C\u91CD\u8907\u307E\u305F\u306F\u7AF6\u5408\u3057\u3066\u3044\u307E\u3059", onTok); } return { onErrorSkip: true, errorTable, rejectLimit }; } isSoftKeyword(value) { return this.peek().kind === "IDENT" /* IDENT */ && this.peek().value.toUpperCase() === value; } validateUpdateFromAssignments(assignments, sourceAlias, tok) { for (const assignment of assignments) { if (assignment.value.type === "STRING_FUNC") { throw new ParseError( "UPDATE ... FROM \u306E SET \u3067\u306F\u6587\u5B57\u5217\u95A2\u6570\u3092\u76F4\u63A5\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok ); } if (assignment.value.type === "SOURCE_FIELD") { if (assignment.value.alias.toLowerCase() !== sourceAlias.toLowerCase()) { throw new ParseError(`UPDATE ... FROM \u306E SET \u53C2\u7167\u306F\u30BD\u30FC\u30B9 alias ${sourceAlias} \u3067\u4FEE\u98FE\u3057\u3066\u304F\u3060\u3055\u3044`, tok); } continue; } if (this.nodeContainsQualifiedField(assignment.value, sourceAlias)) { throw new ParseError("UPDATE ... FROM \u306E\u30BD\u30FC\u30B9\u5217\u306F SET \u306E\u76F4\u63A5\u5024\u3068\u3057\u3066\u306E\u307F\u53C2\u7167\u3067\u304D\u307E\u3059", tok); } if (assignment.value.type === "SCALAR_SUBQUERY") { throw new ParseError("UPDATE ... FROM \u306E SET \u3067\u306F\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } if (this.nodeContainsAnyQualifier(assignment.value)) { throw new ParseError("UPDATE ... FROM \u306E\u30BF\u30FC\u30B2\u30C3\u30C8\u5F0F\u3067\u306F\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u4FEE\u98FE\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044", tok); } } } decomposeUpdateFromWhere(where, targetAppId, sourceAlias, tok) { const leaves = this.flattenTopLevelAnd(where); const joins = []; leaves.forEach((leaf, index) => { const matched = this.matchUpdateFromJoin(leaf, targetAppId, sourceAlias); if (matched !== null) joins.push({ index, ...matched }); }); if (joins.length !== 1) { throw new ParseError("UPDATE ... FROM \u306E WHERE \u306B\u306F target.key = source.key \u306E\u7D50\u5408\u7B49\u5024\u304C\u3061\u3087\u3046\u30691\u3064\u5FC5\u8981\u3067\u3059", tok); } const join = joins[0]; for (let i = 0; i < leaves.length; i++) { if (i !== join.index && this.nodeContainsQualifiedField(leaves[i], sourceAlias)) { throw new ParseError("UPDATE ... FROM \u306E\u30BD\u30FC\u30B9 alias \u306F\u7D50\u5408\u7B49\u5024\u4EE5\u5916\u306E WHERE \u6761\u4EF6\u3067\u306F\u53C2\u7167\u3067\u304D\u307E\u305B\u3093", tok); } if (i !== join.index && this.nodeContainsForeignQualifier(leaves[i], targetAppId)) { throw new ParseError(`UPDATE ... FROM \u306E\u30BF\u30FC\u30B2\u30C3\u30C8\u30D5\u30A3\u30EB\u30BF\u306F APP${targetAppId} \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u3060\u3051\u3092\u53C2\u7167\u3067\u304D\u307E\u3059`, tok); } } const filters = leaves.filter((_, index) => index !== join.index); const targetFilter = filters.reduce( (acc, expr) => acc === null ? expr : { type: "LOGICAL", op: "AND", left: acc, right: expr }, null ); return { targetJoinField: join.targetField, joinKeyField: join.sourceField, targetFilter }; } flattenTopLevelAnd(expr) { if (expr.type === "GROUP") return this.flattenTopLevelAnd(expr.expr); if (expr.type === "LOGICAL" && expr.op === "AND") { return [...this.flattenTopLevelAnd(expr.left), ...this.flattenTopLevelAnd(expr.right)]; } return [expr]; } matchUpdateFromJoin(expr, targetAppId, sourceAlias) { if (expr.type !== "BINARY" || expr.op !== "=" || expr.left.type !== "FIELD") return null; const right = expr.right.type === "ARITH_VALUE" && expr.right.expr.type === "FIELD_REF" ? this.splitQualifiedField(expr.right.expr.field) : null; if (right === null) return null; const left = { alias: expr.left.tableAlias, field: expr.left.field }; if (this.isTargetRef(left, targetAppId) && this.isSourceRef(right, sourceAlias)) { return { targetField: left.field, sourceField: right.field }; } if (this.isSourceRef(left, sourceAlias) && this.isTargetRef(right, targetAppId)) { return { targetField: right.field, sourceField: left.field }; } return null; } splitQualifiedField(field) { const dot = field.indexOf("."); return dot < 0 ? { alias: null, field } : { alias: field.slice(0, dot), field: field.slice(dot + 1) }; } isTargetRef(ref, appId) { return ref.alias === null || ref.alias.toLowerCase() === `app${appId}`.toLowerCase(); } isSourceRef(ref, alias) { return ref.alias?.toLowerCase() === alias.toLowerCase(); } nodeContainsQualifiedField(node, alias) { if (Array.isArray(node)) return node.some((v) => this.nodeContainsQualifiedField(v, alias)); if (node === null || typeof node !== "object") return false; const obj = node; if (obj["type"] === "FIELD" && typeof obj["tableAlias"] === "string" && obj["tableAlias"].toLowerCase() === alias.toLowerCase()) return true; if (obj["type"] === "FIELD_REF" && typeof obj["field"] === "string") { const ref = this.splitQualifiedField(obj["field"]); if (this.isSourceRef(ref, alias)) return true; } return Object.values(obj).some((v) => this.nodeContainsQualifiedField(v, alias)); } nodeContainsForeignQualifier(node, targetAppId) { if (Array.isArray(node)) return node.some((v) => this.nodeContainsForeignQualifier(v, targetAppId)); if (node === null || typeof node !== "object") return false; const obj = node; const expected = `app${targetAppId}`.toLowerCase(); if (obj["type"] === "FIELD" && typeof obj["tableAlias"] === "string") { return obj["tableAlias"].toLowerCase() !== expected; } if (obj["type"] === "FIELD_REF" && typeof obj["field"] === "string") { const ref = this.splitQualifiedField(obj["field"]); if (ref.alias !== null) return ref.alias.toLowerCase() !== expected; } return Object.values(obj).some((v) => this.nodeContainsForeignQualifier(v, targetAppId)); } nodeContainsAnyQualifier(node) { if (Array.isArray(node)) return node.some((v) => this.nodeContainsAnyQualifier(v)); if (node === null || typeof node !== "object") return false; const obj = node; if (obj["type"] === "FIELD" && typeof obj["tableAlias"] === "string") return true; if (obj["type"] === "FIELD_REF" && typeof obj["field"] === "string") { if (this.splitQualifiedField(obj["field"]).alias !== null) return true; } return Object.values(obj).some((v) => this.nodeContainsAnyQualifier(v)); } parseAssignments() { const assignments = []; do { const field = this.parseIdentifier(); this.expect("=" /* EQ */); const value = this.parseAssignmentValue(); assignments.push({ field, value }); } while (this.consume("," /* COMMA */)); return assignments; } /** * SET の右辺を解析する。 * 文字列・kintone 関数はそのまま SqlValue として処理し、 * 数値・フィールド参照・括弧が先頭なら算術式パーサーに渡す。 */ parseAssignmentValue() { const tok = this.peek(); if (this.hasTopLevelTokenBeforeValueEnd("||" /* CONCAT_OP */)) { const expr = this.parseScalarValueExpr(); if (expr.type === "CONCAT_OP" || expr.type === "SCALAR_ARITH" || expr.type === "STRING_FUNC") return expr; if (expr.type === "CASE_WHEN") return { type: "CASE_VALUE", expr }; throw new ParseError("SET \u306E\u5024\u306B\u306F\u9023\u7D50\u3092\u542B\u3080\u30B9\u30AB\u30E9\u30FC\u5024\u5F0F\u304C\u5FC5\u8981\u3067\u3059", tok); } if (tok.kind === "VARIABLE" /* VARIABLE */) return this.parseSqlValue(); if (tok.kind === "STRING" /* STRING */) return this.parseSqlValue(); if (isContextualFunctionToken(tok.kind)) return this.parseSqlValue(); if (tok.kind === "IN" /* IN */) return this.parseSqlValue(); if (tok.kind === "CASE" /* CASE */ || tok.kind === "IF" /* IF */) { return this.parseSqlValue(); } if (tok.kind === "[" /* LBRACKET */) return this.parseArrayLiteral(); if (tok.kind === "(" /* LPAREN */ && this.peekAt(1).kind === "SELECT" /* SELECT */) { this.advance(); const query = this.parseSelect(); this.expect(")" /* RPAREN */); return { type: "SCALAR_SUBQUERY", query }; } const previousAllowUnaryPlusNumber = this.allowUnaryPlusNumber; this.allowUnaryPlusNumber = true; let node; try { node = this.parseArithAddSub(); } finally { this.allowUnaryPlusNumber = previousAllowUnaryPlusNumber; } if (node.type === "NUMBER") return node; if (node.type === "ARITH") return node; if (node.type === "STRING_FUNC") return node; if (node.type === "FIELD_REF") { const dot = node.field.indexOf("."); if (dot > 0 && dot < node.field.length - 1) { return { type: "SOURCE_FIELD", alias: node.field.slice(0, dot), field: node.field.slice(dot + 1) }; } } throw new ParseError( "SET \u306E\u5024\u306B\u30D5\u30A3\u30FC\u30EB\u30C9\u53C2\u7167\u3092\u5358\u72EC\u3067\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093", tok ); } parseArithOp() { const tok = this.advance(); switch (tok.kind) { case "+" /* PLUS */: return "+"; case "-" /* MINUS */: return "-"; case "*" /* STAR */: return "*"; case "/" /* SLASH */: return "/"; case "%" /* PERCENT */: return "%"; default: throw new ParseError("\u7B97\u8853\u6F14\u7B97\u5B50\uFF08+ - * / %\uFF09\u304C\u5FC5\u8981\u3067\u3059", tok); } } // ---------------------------------------------------------- // DELETE // ---------------------------------------------------------- parseDelete() { this.expect("DELETE" /* DELETE */); this.expect("FROM" /* FROM */); this.rejectTempTableDml(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); const whereTok = this.peek(); if (!this.consume("WHERE" /* WHERE */)) { throw new ParseError( "DELETE \u6587\u306B\u306F WHERE \u53E5\u304C\u5FC5\u9808\u3067\u3059\uFF08\u5168\u4EF6\u524A\u9664\u3092\u9632\u3050\u305F\u3081\uFF09", whereTok ); } const where = this.parseWhereExpr(); return subtableCode ? { type: "DELETE", appId, subtableCode, where } : { type: "DELETE", appId, where }; } // ---------------------------------------------------------- // REORDER // ---------------------------------------------------------- parseReorder() { this.expect("REORDER" /* REORDER */); const all = this.consume("ALL" /* ALL */); this.rejectTempTableDml(); const name = this.parseIdentifier(); const { appId, subtableCode } = extractTableRef(name, this.prev()); if (!subtableCode) { throw new ParseError("REORDER \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB\u306E\u307F\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08\u4F8B: REORDER APP100$\u660E\u7D30 ...\uFF09", this.prev()); } this.expect("BY" /* BY */); const by = this.parseOrderBy(); if (by.length === 0) { throw new ParseError("REORDER \u306B\u306F BY \u30AD\u30FC\u304C\u5FC5\u8981\u3067\u3059", this.prev()); } let where = null; if (all) { if (this.peek().kind === "WHERE" /* WHERE */) { throw new ParseError("REORDER ALL \u3067\u306F WHERE \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093", this.peek()); } } else { const whereTok = this.peek(); if (!this.consume("WHERE" /* WHERE */)) { throw new ParseError("REORDER \u306B\u306F WHERE \u53E5\u304C\u5FC5\u9808\u3067\u3059\uFF08\u8AA4\u64CD\u4F5C\u9632\u6B62\uFF09", whereTok); } where = this.parseWhereExpr(); } return { type: "REORDER", appId, subtableCode, all, by, where }; } // ---------------------------------------------------------- // トークン操作ヘルパー // ---------------------------------------------------------- peek() { return this.tokens[this.pos] ?? { kind: "EOF" /* EOF */, value: "", pos: -1 }; } /** n 先のトークンを読み取る(消費しない) */ peekAt(n) { return this.tokens[this.pos + n] ?? { kind: "EOF" /* EOF */, value: "", pos: -1 }; } prev() { return this.tokens[this.pos - 1] ?? { kind: "EOF" /* EOF */, value: "", pos: -1 }; } advance() { const tok = this.peek(); if (tok.kind !== "EOF" /* EOF */) this.pos++; return tok; } /** 指定 kind なら消費して true を返す */ consume(kind) { if (this.peek().kind === kind) { this.advance(); return true; } return false; } /** 指定 kind でなければエラー */ expect(kind, msg) { const tok = this.peek(); if (tok.kind !== kind) { throw new ParseError( msg ?? `\u300C${kind}\u300D\u304C\u5FC5\u8981\u3067\u3059`, tok ); } return this.advance(); } /** FROM / GROUP BY など文脈付きエラーメッセージ */ expectKeyword(kind, msg) { return this.expect(kind, msg); } /** 符号なし整数を読む */ parseUnsignedInt() { const tok = this.expect("NUMBER" /* NUMBER */, "\u6574\u6570\u304C\u5FC5\u8981\u3067\u3059"); const n = Number(tok.value); if (!Number.isInteger(n) || n < 0) { throw new ParseError("\u6B63\u306E\u6574\u6570\u304C\u5FC5\u8981\u3067\u3059", tok); } return n; } // 識別子(IDENT / BIDENT)を読む。# 始まりの一時テーブル名は不可 //(temp マーカーはレキサが生成する IDENT のみ。`#field` のような // バッククォート識別子は # で始まる通常フィールド名として許容する) parseIdentifier() { const tok = this.peek(); if (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) { if (tok.kind === "IDENT" /* IDENT */ && tok.value.startsWith("#")) { throw new ParseError( "\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u540D\uFF08# \u3067\u59CB\u307E\u308B\u540D\u524D\uFF09\u306F FROM / JOIN / CREATE / DROP TEMP TABLE \u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059", tok ); } this.advance(); return tok.value; } throw new ParseError( "\u30D5\u30A3\u30FC\u30EB\u30C9\u540D\u307E\u305F\u306F\u30C6\u30FC\u30D6\u30EB\u540D\u304C\u5FC5\u8981\u3067\u3059", tok ); } // テーブル名(IDENT / BIDENT)を読む。# 始まりの一時テーブル名を許容する //(一時テーブルを受理してよいのはテーブル参照位置のみ。他は parseIdentifier を使う) parseTableName() { const tok = this.peek(); if (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */) { this.advance(); return tok.value; } throw new ParseError( "\u30D5\u30A3\u30FC\u30EB\u30C9\u540D\u307E\u305F\u306F\u30C6\u30FC\u30D6\u30EB\u540D\u304C\u5FC5\u8981\u3067\u3059", tok ); } // DML の対象テーブル位置に一時テーブルが指定されていたら拒否する rejectTempTableDml() { const tok = this.peek(); if (tok.kind === "IDENT" /* IDENT */ && tok.value.startsWith("#")) { throw new ParseError( `DML on temp table ${tok.value} is not supported.`, tok ); } } // エイリアス名: IDENT / BIDENT に加え、キーワードも許容する // 例: SELECT SUM(金額) AS avg → "avg" は AVG キーワードだが alias として有効 parseAliasName() { const tok = this.peek(); if (tok.value.startsWith("#")) { throw new ParseError("\u30A8\u30A4\u30EA\u30A2\u30B9\u540D\u306B # \u3067\u59CB\u307E\u308B\u540D\u524D\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093", tok); } if (tok.kind === "IDENT" /* IDENT */ || tok.kind === "BIDENT" /* BIDENT */ || KEYWORDS.has(tok.value.toUpperCase())) { this.advance(); return tok.value.toLowerCase(); } throw new ParseError("\u30A8\u30A4\u30EA\u30A2\u30B9\u540D\u304C\u5FC5\u8981\u3067\u3059", tok); } /** フィールド名または修飾フィールド名(alias.field)を解析する */ parseFieldPath() { const first = this.parseIdentifier(); if (this.peek().kind !== "." /* DOT */) return first; this.advance(); const second = this.parseIdentifier(); return `${first}.${second}`; } /** SELECT 列用: alias.field に加えて _p.* / _parent.* を受け付ける */ parseColumnFieldRef() { const first = this.parseIdentifier(); if (this.peek().kind !== "." /* DOT */) return first; this.advance(); if (this.consume("*" /* STAR */)) { return `${first}.*`; } const second = this.parseIdentifier(); return `${first}.${second}`; } }; function normalizeCastType(raw) { const upper = raw.toUpperCase(); const textTypes = /* @__PURE__ */ new Set(["TEXT", "VARCHAR", "CHAR", "NCHAR", "NVARCHAR", "STRING"]); const numberTypes = /* @__PURE__ */ new Set([ "NUMBER", "INT", "INTEGER", "NUMERIC", "DECIMAL", "FLOAT", "DOUBLE", "REAL", "BIGINT", "SMALLINT" ]); if (textTypes.has(upper)) return "TEXT"; if (numberTypes.has(upper)) return "NUMBER"; return null; } function extractTableRef(name, tok) { const m = name.match(/^[Aa][Pp][Pp](\d+)(?:\$(.+))?$/); if (!m) { throw new ParseError( `\u30C6\u30FC\u30D6\u30EB\u540D\u306F APP + \u6570\u5B57\uFF08\u307E\u305F\u306F APP + \u6570\u5B57 + $\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\uFF09\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u4F8B: APP100 / APP100$\u660E\u7D30\uFF09\u3002\u300C${name}\u300D\u306F\u7121\u52B9\u3067\u3059`, tok ); } return { appId: Number(m[1]), subtableCode: m[2] ?? null }; } // src/core/batch.ts init_define_KSQL_DOCS(); // src/core/dmlGuard.ts init_define_KSQL_DOCS(); function getStatementType(stmt) { if (!stmt || typeof stmt !== "object") return "UNKNOWN"; const obj = stmt; return typeof obj.type === "string" ? obj.type : "UNKNOWN"; } function isDmlType(type) { return type === "INSERT" || type === "INSERT_SELECT" || type === "UPDATE" || type === "DELETE" || type === "UPSERT" || type === "UPSERT_SELECT" || type === "REORDER" || type === "IMPORT"; } function isReadOnlyType(type) { return type === "SELECT" || type === "VALIDATE" || type === "UNION" || type === "WITH" || type === "EXPLAIN" || type === "SHOW_APPS" || type === "DESCRIBE" || type === "CREATE_TEMP_TABLE" || type === "DROP_TEMP_TABLE" || type === "SET_VARIABLE" || type === "DECLARE_VARIABLE" || type === "ASSERT"; } function writesKintone(stmt) { return isDmlType(stmt.type) && !("validateOnly" in stmt && stmt.validateOnly === true); } function isReadOnlyStatement(stmt) { return !writesKintone(stmt) && (isReadOnlyType(stmt.type) || isDmlType(stmt.type)); } var STATISTICAL_AGGREGATES = /* @__PURE__ */ new Set([ "STDDEV_POP", "STDDEV_SAMP", "VAR_POP", "VAR_SAMP", "MEDIAN", "MODE" ]); function addReasons(target, source) { for (const reason of source) target.add(reason); } function containsStatisticalAggregate(value, seen = /* @__PURE__ */ new Set()) { if (value === null || typeof value !== "object") return false; if (seen.has(value)) return false; seen.add(value); const record2 = value; if ((record2.type === "AGGREGATE" || record2.type === "AGG_REF") && typeof record2.func === "string" && STATISTICAL_AGGREGATES.has(record2.func)) return true; if (record2.type === "FIELD" && typeof record2.field === "string" && /^(STDDEV_POP|STDDEV_SAMP|VAR_POP|VAR_SAMP|MEDIAN|MODE)\(/i.test(record2.field)) return true; return Object.values(record2).some((child) => Array.isArray(child) ? child.some((entry) => containsStatisticalAggregate(entry, seen)) : containsStatisticalAggregate(child, seen)); } function completeInputReasons(stmt) { const reasons = /* @__PURE__ */ new Set(); if (isDmlType(stmt.type)) { reasons.add("DML"); return reasons; } switch (stmt.type) { case "VALIDATE": reasons.add("VALIDATE"); break; case "SELECT": addReasons(reasons, selectCompleteInputReasons(stmt)); break; case "UNION": addReasons(reasons, unionCompleteInputReasons(stmt)); break; case "WITH": for (const cte of stmt.ctes) { addReasons(reasons, completeInputReasons(cte.query)); } addReasons(reasons, completeInputReasons(stmt.query)); break; case "CREATE_TEMP_TABLE": addReasons(reasons, completeInputReasons(stmt.query)); break; default: break; } if (containsStatisticalAggregate(stmt)) reasons.add("STATISTICAL_AGGREGATE"); return reasons; } function requiresCompleteInput(stmt) { return completeInputReasons(stmt).size > 0; } function unionCompleteInputReasons(stmt) { const reasons = stmt.left.type === "SELECT" ? selectCompleteInputReasons(stmt.left) : unionCompleteInputReasons(stmt.left); addReasons(reasons, selectCompleteInputReasons(stmt.right)); return reasons; } function selectCompleteInputReasons(stmt) { const reasons = /* @__PURE__ */ new Set(); if (stmt.orderBy.length > 0) reasons.add("LOCAL_ORDER"); for (const column of stmt.columns) { if (column.type === "WINDOW_COL" && column.orderBy.length > 0) reasons.add("WINDOW_ORDER"); if (column.type === "SCALAR_SUBQUERY_COL") addReasons(reasons, selectCompleteInputReasons(column.query)); if (column.type === "CASE_COL") { for (const branch of column.expr.branches) addReasons(reasons, whereCompleteInputReasons(branch.condition)); } } addReasons(reasons, whereCompleteInputReasons(stmt.where)); addReasons(reasons, whereCompleteInputReasons(stmt.having)); if (containsStatisticalAggregate(stmt)) reasons.add("STATISTICAL_AGGREGATE"); return reasons; } function whereCompleteInputReasons(where) { const reasons = /* @__PURE__ */ new Set(); if (where === null) return reasons; switch (where.type) { case "BINARY": if (where.right.type === "SUBQUERY_IN_LIST" || where.right.type === "SCALAR_SUBQUERY") { addReasons(reasons, selectCompleteInputReasons(where.right.query)); } break; case "LOGICAL": addReasons(reasons, whereCompleteInputReasons(where.left)); addReasons(reasons, whereCompleteInputReasons(where.right)); break; case "NOT": case "GROUP": addReasons(reasons, whereCompleteInputReasons(where.expr)); break; case "EXISTS": addReasons(reasons, selectCompleteInputReasons(where.query)); break; case "NULL_CHECK": case "BOOLEAN": break; } return reasons; } function hasWhereClause(stmt) { if (!stmt || typeof stmt !== "object") return false; const obj = stmt; return obj.where !== null && obj.where !== void 0; } function isNoFromSelectStatement(stmt) { if (!stmt || typeof stmt !== "object") return false; const obj = stmt; return obj.type === "SELECT" && obj.from?.appId === 0 && obj.from?.cteName === NO_FROM_CTE_NAME; } function getInsertValuesCount(stmt) { if (!stmt || typeof stmt !== "object") return null; const obj = stmt; if (obj.type !== "INSERT") return null; return Array.isArray(obj.values) ? obj.values.length : null; } // src/core/applyPatchScope.ts init_define_KSQL_DOCS(); var APPLY_SYNTAX_CAPABILITIES = Object.freeze({ v1: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH"]), insert: false, upsert: false, multipleBlocks: false, multipleParents: false, idxSelectors: false, expectRows: false, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), "v1.1": Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND"]), insert: false, upsert: false, multipleBlocks: true, multipleParents: false, idxSelectors: false, expectRows: false, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), "v1.2": Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: false, upsert: false, multipleBlocks: true, multipleParents: false, idxSelectors: false, expectRows: false, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase10a: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: false, upsert: false, multipleBlocks: true, multipleParents: true, idxSelectors: false, expectRows: false, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase11: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: false, upsert: false, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: false, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase12: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: false, upsert: false, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase13a: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: true, upsert: false, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase14a: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: true, upsert: true, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase14b: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: true, upsert: true, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase14c: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE"]), insert: true, upsert: true, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase15a: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE", "ADD", "REMOVE_VALUE"]), insert: true, upsert: true, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }), phase15b: Object.freeze({ operations: /* @__PURE__ */ new Set(["PATCH", "APPEND", "REMOVE", "ADD", "REMOVE_VALUE"]), insert: true, upsert: true, multipleBlocks: true, multipleParents: true, idxSelectors: true, expectRows: true, updateFrom: false, check: false, onErrorSkip: false, rejectLimit: false }) }); var APPLY_EXECUTION_CAPABILITIES = Object.freeze({ phase10a: Object.freeze({ multipleParentPreflight: false, internalPreparedWrite: false, publicMultipleParentWrite: false, insertWrite: false, upsertWrite: false }), phase10b: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: false, publicMultipleParentWrite: false, insertWrite: false, upsertWrite: false }), phase10c: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: false, insertWrite: false, upsertWrite: false }), phase10d: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: false, upsertWrite: false }), phase11: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: false, upsertWrite: false }), phase12: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: false, upsertWrite: false }), phase13a: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: false, upsertWrite: false }), phase13b: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: false, upsertWrite: false }), phase13c: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: true, upsertWrite: false }), phase14a: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: true, upsertWrite: false }), phase14b: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: true, upsertWrite: false }), phase14c: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: true, upsertWrite: true }), phase15a: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: true, upsertWrite: true }), phase15b: Object.freeze({ multipleParentPreflight: true, internalPreparedWrite: true, publicMultipleParentWrite: true, insertWrite: true, upsertWrite: true }) }); var activeVersion = "v1"; function unsupported(feature) { throw new Error(`UnsupportedError: APPLY ${activeVersion} scope does not support ${feature}`); } function withVersion(version2, run) { const previous = activeVersion; activeVersion = version2; try { return run(); } finally { activeVersion = previous; } } function statementWithApply(statement) { const target = statement.type === "EXPLAIN" ? statement.query : statement; if (target.type === "UPDATE" || target.type === "INSERT") { return target.applyBlocks?.length ? target : null; } if (target.type === "UPSERT") { return target.onInsertApplyBlocks?.length || target.onUpdateApplyBlocks?.length ? target : null; } return null; } function assertApplyScope(version2, statement) { return withVersion(version2, () => assertApplyScopeForCapabilities(statement, APPLY_SYNTAX_CAPABILITIES[version2])); } function assertApplyScopeForCapabilities(statement, capabilities) { const applyStatement = statementWithApply(statement); if (applyStatement === null) return; if (applyStatement.type === "UPSERT") { assertUpsertApplyScope(applyStatement, capabilities); return; } const blocks = applyStatement.applyBlocks; assertUniqueApplyBlocks(blocks); if (!capabilities.multipleBlocks && blocks.length !== 1) unsupported("multiple APPLY blocks in this phase"); if (applyStatement.type === "INSERT") { assertInsertApplyScope(applyStatement, blocks, capabilities); return; } const update = applyStatement; if (update.subtableCode) unsupported("a subtable UPDATE as the parent statement in this phase"); if (!capabilities.updateFrom && update.from != null) unsupported("UPDATE ... FROM in this phase"); if (!capabilities.check && update.checkGroups?.length) unsupported("CHECK in this phase"); if (!capabilities.onErrorSkip && update.onErrorSkip) unsupported("ON ERROR SKIP in this phase"); if (!capabilities.rejectLimit && update.rejectLimit != null) unsupported("REJECT LIMIT in this phase"); assertSafeParentWhere(update.where, capabilities.multipleParents); assertUpdateApplyOperations(blocks, capabilities); } function assertUpdateApplyOperations(blocks, capabilities) { for (const block of blocks) { for (const operation of block.operations) { if (!capabilities.operations.has(operation.kind)) unsupported(`${operation.kind} in this phase`); } assertApplyBlockOperationFamily(block); for (const operation of block.operations) { if (operation.kind === "APPEND") { for (const field of operation.fields) assertSafeChildField(field, "APPEND targets"); assertSafeApplyNode(operation.values, "APPEND values"); continue; } if (operation.kind === "REMOVE") { if (!capabilities.expectRows && operation.expectRows) unsupported("EXPECT ROWS in this phase"); if (operation.selector.kind === "WHERE") { assertSafeChildPredicate(operation.selector.where, capabilities.idxSelectors); } continue; } if (operation.kind !== "PATCH") continue; if (!capabilities.expectRows && operation.expectRows) unsupported("EXPECT ROWS in this phase"); if (operation.assignments.length === 0) unsupported("an empty PATCH operation in this phase"); for (const assignment of operation.assignments) { if (assignment.field.startsWith("_") || assignment.field.startsWith("$")) { throw new Error(`ArgumentError: APPLY assignment target ${assignment.field} is a system field.`); } if (assignment.field.includes(".")) { unsupported("parent or qualified PATCH targets in this phase"); } } assertSafeApplyNode(operation.assignments, "PATCH assignments"); if (operation.selector.kind === "WHERE") { assertSafeChildPredicate(operation.selector.where, capabilities.idxSelectors); } } } } function assertApplyBlockOperationFamily(block) { const hasSubtableOperation = block.operations.some( (operation) => operation.kind === "PATCH" || operation.kind === "APPEND" || operation.kind === "REMOVE" ); const hasMultiValueOperation = block.operations.some( (operation) => operation.kind === "ADD" || operation.kind === "REMOVE_VALUE" ); if (hasSubtableOperation && hasMultiValueOperation) { throw new Error("ArgumentError: APPLY block cannot mix row operations and multi-value operations."); } const expectedKind = hasMultiValueOperation ? "MULTI_VALUE" : "SUBTABLE"; if (block.targetKind !== expectedKind) { throw new Error(`ArgumentError: APPLY block target kind ${String(block.targetKind)} does not match ${expectedKind} operations.`); } } var MULTI_VALUE_FIELD_TYPES = /* @__PURE__ */ new Set([ "MULTI_SELECT", "CHECK_BOX", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT" ]); function assertApplyTargetFieldType(block, fieldType) { assertApplyBlockOperationFamily(block); if (block.targetKind === "MULTI_VALUE") { if (!MULTI_VALUE_FIELD_TYPES.has(fieldType)) { throw new Error(`ArgumentError: APPLY multi-value operations require MULTI_SELECT, CHECK_BOX, USER_SELECT, ORGANIZATION_SELECT, or GROUP_SELECT target; ${block.field} is ${fieldType}.`); } return; } if (fieldType !== "SUBTABLE") { throw new Error(`ArgumentError: APPLY row operations require a SUBTABLE target; ${block.field} is ${fieldType}.`); } } function assertUniqueApplyBlocks(blocks) { const seen = /* @__PURE__ */ new Set(); for (const block of blocks) { if (seen.has(block.field)) { throw new Error(`ArgumentError: APPLY ${activeVersion} scope allows only one block for table ${block.field}`); } seen.add(block.field); } } function assertUpsertApplyScope(upsert, capabilities) { if (!capabilities.upsert) unsupported("UPSERT in this phase"); if (!capabilities.check && upsert.checkGroups?.length) unsupported("CHECK in this phase"); if (!capabilities.onErrorSkip && upsert.onErrorSkip) unsupported("ON ERROR SKIP in this phase"); if (!capabilities.rejectLimit && upsert.rejectLimit != null) unsupported("REJECT LIMIT in this phase"); const insertBlocks = upsert.onInsertApplyBlocks ?? []; const updateBlocks = upsert.onUpdateApplyBlocks ?? []; assertUniqueApplyBlocks(insertBlocks); assertUniqueApplyBlocks(updateBlocks); if (!capabilities.multipleBlocks && (insertBlocks.length > 1 || updateBlocks.length > 1)) { unsupported("multiple APPLY blocks in this phase"); } assertAppendOnlyBlocks(insertBlocks, "UPSERT ON INSERT"); assertUpdateApplyOperations(updateBlocks, { ...capabilities, idxSelectors: false, expectRows: false }); } function assertAppendOnlyBlocks(blocks, parent) { for (const block of blocks) { for (const operation of block.operations) { if (operation.kind !== "APPEND") unsupported(`${operation.kind} for ${parent} in this phase`); for (const field of operation.fields) assertSafeChildField(field, "APPEND targets"); assertSafeApplyNode(operation.values, "APPEND values"); } } } function assertInsertApplyScope(insert, blocks, capabilities) { if (!capabilities.insert) unsupported("INSERT in this phase"); if (insert.subtableCode) unsupported("a subtable INSERT as the parent statement in this phase"); if (!capabilities.check && insert.checkGroups?.length) unsupported("CHECK in this phase"); if (!capabilities.onErrorSkip && insert.onErrorSkip) unsupported("ON ERROR SKIP in this phase"); if (!capabilities.rejectLimit && insert.rejectLimit != null) unsupported("REJECT LIMIT in this phase"); assertAppendOnlyBlocks(blocks, "INSERT"); } function isSinglePositiveRecordIdWhere(where) { if (where.type !== "BINARY" || where.op !== "=" || where.left.type !== "FIELD" || where.left.tableAlias !== null || where.left.field !== "$id" || where.right.type !== "NUMBER") { return false; } const raw = where.right.raw ?? String(where.right.value); return /^\d+$/.test(raw) && where.right.value > 0 && Number.isSafeInteger(where.right.value); } function assertApplyExecutionScope(phase, statement) { const capabilities = APPLY_EXECUTION_CAPABILITIES[phase]; const isValidationOnly = "validateOnly" in statement && statement.validateOnly === true; if (statement.type !== "EXPLAIN" && !isValidationOnly && statementHasMultiValueApply(statement) && phase !== "phase15b") { throw new Error(`UnsupportedError: APPLY ${formatExecutionPhase(phase)} multi-value execution is not connected`); } if (statement.type === "UPSERT" && (statement.onInsertApplyBlocks?.length || statement.onUpdateApplyBlocks?.length)) { if (statement.validateOnly !== true && !capabilities.upsertWrite) { throw new Error(`UnsupportedError: APPLY ${formatExecutionPhase(phase)} UPSERT execution is not connected`); } return; } if (statement.type === "INSERT" && statement.applyBlocks?.length) { if (statement.validateOnly !== true && !capabilities.insertWrite) { throw new Error(`UnsupportedError: APPLY ${formatExecutionPhase(phase)} INSERT execution is not connected`); } return; } if (statement.type !== "UPDATE" || !statement.applyBlocks?.length) return; if (!capabilities.multipleParentPreflight && !isSinglePositiveRecordIdWhere(statement.where)) { throw new Error(`UnsupportedError: APPLY ${formatExecutionPhase(phase)} execution does not support multiple-parent APPLY`); } } function statementHasMultiValueApply(statement) { const target = statement.type === "EXPLAIN" ? statement.query : statement; const blocks = target.type === "UPDATE" || target.type === "INSERT" ? target.applyBlocks ?? [] : target.type === "UPSERT" ? [...target.onInsertApplyBlocks ?? [], ...target.onUpdateApplyBlocks ?? []] : []; return blocks.some((block) => block.targetKind === "MULTI_VALUE" || block.operations.some((operation) => operation.kind === "ADD" || operation.kind === "REMOVE_VALUE")); } function assertApplyPublicWriteScope(phase, statement) { if (statement.type !== "UPDATE" || !statement.applyBlocks?.length || isSinglePositiveRecordIdWhere(statement.where)) return; if (!APPLY_EXECUTION_CAPABILITIES[phase].publicMultipleParentWrite) { throw new Error(`UnsupportedError: APPLY ${formatExecutionPhase(phase)} public multiple-parent write is not connected`); } } function assertApplyInternalWriteScope(phase) { if (!APPLY_EXECUTION_CAPABILITIES[phase].internalPreparedWrite) { throw new Error(`UnsupportedError: APPLY ${formatExecutionPhase(phase)} internal prepared write is not available`); } } function formatExecutionPhase(phase) { return `Phase ${phase.slice("phase".length)}`; } function assertSafeParentWhere(where, multipleParents) { if (isSinglePositiveRecordIdWhere(where)) return; if (where.type === "BINARY" && where.op === "=" && where.left.type === "FIELD" && where.left.tableAlias === null && where.left.field === "$id") { unsupported("a parent $id that is not a positive safe integer in this phase"); } if (!multipleParents) { unsupported("a parent WHERE other than the single condition $id = in this phase"); } assertSafeParentPredicateNode(where, multipleParents); } function assertSafeParentPredicateNode(node, allowKlike) { if (Array.isArray(node)) { for (const value of node) assertSafeParentPredicateNode(value, allowKlike); return; } if (node === null || typeof node !== "object") return; const item = node; const type = typeof item["type"] === "string" ? item["type"] : null; const op = typeof item["op"] === "string" ? item["op"] : null; if (!allowKlike && (op === "KLIKE" || op === "NOT_KLIKE")) unsupported("KLIKE in parent WHERE"); if (type === "SELECT" || type === "SCALAR_SUBQUERY" || type === "SUBQUERY_IN_LIST" || type === "EXISTS") { unsupported("subqueries in parent WHERE"); } if (type === "WINDOW_COL" || type === "AGGREGATE" || type === "AGG_REF" || type === "AGG_ARITH" || type === "ARITH_AGG_COL") unsupported("aggregate or window expressions in parent WHERE"); if ((type === "FIELD" || type === "FIELD_REF") && typeof item["field"] === "string" && /^(count|sum|avg|min|max|group_concat)\s*\(/i.test(item["field"])) { unsupported("aggregate or window expressions in parent WHERE"); } if (type === "KINTONE_FUNC") unsupported("non-deterministic kintone functions in parent WHERE"); for (const value of Object.values(item)) assertSafeParentPredicateNode(value, allowKlike); } function assertSafeChildPredicate(where, idxSelectors) { assertSafeApplyNode(where, "child row selectors", idxSelectors); } function assertSafeApplyNode(node, context, allowIdx = false) { if (Array.isArray(node)) { for (const value of node) assertSafeApplyNode(value, context, allowIdx); return; } if (node === null || typeof node !== "object") return; const item = node; const type = typeof item["type"] === "string" ? item["type"] : null; const kind = typeof item["kind"] === "string" ? item["kind"] : null; const op = typeof item["op"] === "string" ? item["op"] : null; if (op === "KLIKE" || op === "NOT_KLIKE") unsupported(`KLIKE in ${context}`); if (type === "SELECT" || type === "SCALAR_SUBQUERY" || type === "SUBQUERY_IN_LIST" || type === "EXISTS") { unsupported(`subqueries in ${context}`); } if (type === "WINDOW_COL" || type === "AGGREGATE" || type === "AGG_REF" || type === "AGG_ARITH" || type === "ARITH_AGG_COL") unsupported(`aggregate or window expressions in ${context}`); if (type === "KINTONE_FUNC") unsupported(`non-deterministic kintone functions in ${context}`); if (type === "FIELD") { const alias = item["tableAlias"]; const field = item["field"]; if (alias !== null && alias !== void 0) unsupported(`qualified or parent field references in ${context}`); assertSafeChildField(field, context, allowIdx); } if (type === "FIELD_REF") assertSafeChildField(item["field"], context, allowIdx); if (kind === "PATCH" || kind === "APPEND" || kind === "REMOVE") { return; } for (const value of Object.values(item)) assertSafeApplyNode(value, context, allowIdx); } function assertSafeChildField(field, context, allowIdx = false) { if (typeof field !== "string") return; const lower = field.toLowerCase(); if (lower === "_idx" && !allowIdx) unsupported(`_idx in ${context}`); if (lower.startsWith("_p.") || lower.includes(".")) unsupported(`parent or qualified field references in ${context}`); if (/^(count|sum|avg|min|max|group_concat)\s*\(/i.test(field)) { unsupported(`aggregate expressions in ${context}`); } } // src/core/klikeValidation.ts init_define_KSQL_DOCS(); // src/converter/selectToKintone.ts init_define_KSQL_DOCS(); // src/converter/whereToKintone.ts init_define_KSQL_DOCS(); // src/engine/pushDownNot.ts init_define_KSQL_DOCS(); function pushDownNot(expr) { switch (expr.type) { case "BOOLEAN": return { type: "BOOLEAN", value: !expr.value }; case "BINARY": { const negated = negateOp(expr.op); if (negated === null) { throw new KintoneQueryError( `NOT ${expr.op} \u306F\u30B5\u30DD\u30FC\u30C8\u5BFE\u8C61\u5916\u3067\u3059` ); } return { ...expr, op: negated }; } case "NULL_CHECK": return { ...expr, not: !expr.not }; case "LOGICAL": return { type: "LOGICAL", op: expr.op === "AND" ? "OR" : "AND", left: pushDownNot(expr.left), right: pushDownNot(expr.right) }; case "NOT": return expr.expr; // 二重否定 case "GROUP": return { type: "GROUP", expr: pushDownNot(expr.expr) }; case "EXISTS": return { ...expr, not: !expr.not }; } } function negateOp(op) { switch (op) { case "=": return "!="; case "!=": case "<>": return "="; case ">": return "<="; case "<": return ">="; case ">=": return "<"; case "<=": return ">"; case "LIKE": return "NOT_LIKE"; case "NOT_LIKE": return "LIKE"; case "KLIKE": return "NOT_KLIKE"; case "NOT_KLIKE": return "KLIKE"; case "IN": return "NOT_IN"; case "NOT_IN": return "IN"; } } // src/core/like.ts init_define_KSQL_DOCS(); function likePatternHasWildcard(pattern) { return pattern.includes("%") || pattern.includes("_"); } function isLike(where) { return where.type === "BINARY" && (where.op === "LIKE" || where.op === "NOT_LIKE"); } function isKlike(where) { return where.type === "BINARY" && (where.op === "KLIKE" || where.op === "NOT_KLIKE"); } function whereHasLike(where) { if (where === null) return false; if (isLike(where)) return true; switch (where.type) { case "LOGICAL": return whereHasLike(where.left) || whereHasLike(where.right); case "NOT": case "GROUP": return whereHasLike(where.expr); case "BINARY": case "NULL_CHECK": case "EXISTS": case "BOOLEAN": return false; } } function whereHasKlike(where) { if (where === null) return false; if (isKlike(where)) return true; switch (where.type) { case "LOGICAL": return whereHasKlike(where.left) || whereHasKlike(where.right); case "NOT": case "GROUP": return whereHasKlike(where.expr); case "BINARY": case "NULL_CHECK": case "EXISTS": case "BOOLEAN": return false; } } // src/converter/whereToKintone.ts function whereToKintone(expr) { switch (expr.type) { case "BINARY": return convertBinary(expr); case "NULL_CHECK": return convertNullCheck(expr); case "LOGICAL": return convertLogical(expr); case "NOT": return convertNot(expr); case "GROUP": return convertGroup(expr); case "EXISTS": throw new KintoneQueryError("EXISTS \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); case "BOOLEAN": throw new KintoneQueryError("internal error: BOOLEAN predicate reached kintone query conversion"); } } function convertBinary(expr) { if (isLike(expr)) { throw new KintoneQueryError( "LIKE / NOT LIKE \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093\uFF08\u5E38\u306B JS \u8A55\u4FA1\u304C\u5FC5\u8981\u3067\u3059\uFF09" ); } const left = convertField(expr.left); const op = convertOp(expr.op); const right = convertValue(expr.right, expr.op); return `${left} ${op} ${right}`; } function convertOp(op) { switch (op) { case "=": return "="; case "!=": case "<>": return "!="; case ">": return ">"; case "<": return "<"; case ">=": return ">="; case "<=": return "<="; case "LIKE": return "like"; case "NOT_LIKE": return "not like"; case "KLIKE": return "like"; case "NOT_KLIKE": return "not like"; case "IN": return "in"; case "NOT_IN": return "not in"; } } function convertNullCheck(expr) { const field = convertField(expr.field); return expr.not ? `${field} != ""` : `${field} = ""`; } function convertLogical(expr) { const left = whereToKintone(expr.left); const right = whereToKintone(expr.right); const op = expr.op === "AND" ? "and" : "or"; const leftStr = needsParens(expr.left) ? `(${left})` : left; const rightStr = needsParens(expr.right) ? `(${right})` : right; return `${leftStr} ${op} ${rightStr}`; } function convertNot(expr) { return whereToKintone(pushDownNot(expr.expr)); } function convertGroup(expr) { return `(${whereToKintone(expr.expr)})`; } function convertField(field) { if (field.type === "FUNC_FIELD") { throw new KintoneQueryError( `WHERE \u53E5\u306E\u95A2\u6570\uFF08${field.expr.func}\uFF09\u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093` ); } if (field.type === "ARITH_FIELD") { throw new KintoneQueryError("WHERE \u53E5\u306E\u7B97\u8853\u5F0F\u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); } if (field.type === "CASE_FIELD") { throw new KintoneQueryError("WHERE \u53E5\u306E CASE WHEN \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); } return quoteIdentifier(field.field); } function convertValue(value, op) { switch (value.type) { case "VARIABLE": throw new KintoneQueryError(`\u672A\u89E3\u6C7A\u306E\u30D0\u30C3\u30C1\u5909\u6570 @${value.name} \u304C\u3042\u308A\u307E\u3059`); case "VARIABLE_IN_LIST": throw new KintoneQueryError(`\u672A\u89E3\u6C7A\u306E\u914D\u5217\u5909\u6570 @${value.name} \u304C\u3042\u308A\u307E\u3059`); case "STRING": return convertString(value); case "NUMBER": return numberLiteralText(value); case "KINTONE_FUNC": return convertKintoneFunc(value); case "IN_LIST": return convertInList(value, op); case "ARITH_VALUE": throw new KintoneQueryError("WHERE \u53E5\u306E\u53F3\u8FBA\u7B97\u8853\u5F0F\u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); case "CASE_VALUE": throw new KintoneQueryError("WHERE \u53E5\u306E\u53F3\u8FBA CASE WHEN \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); case "SUBQUERY_IN_LIST": throw new KintoneQueryError("IN (SELECT ...) \u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); case "SCALAR_SUBQUERY": throw new KintoneQueryError("\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"); case "ARRAY": throw new KintoneQueryError("\u914D\u5217\u30EA\u30C6\u30E9\u30EB\u306F WHERE \u53E5\u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"); } } function convertString(v) { return `"${v.value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } function convertKintoneFunc(v) { return `${v.name}()`; } function convertInList(v, op) { if (op !== "IN" && op !== "NOT_IN") { throw new KintoneQueryError("IN_LIST \u306F IN / NOT IN \u6F14\u7B97\u5B50\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059"); } assertResolvedInListValues(v.values); const values = v.values.map( (item) => item.type === "STRING" ? convertString(item) : numberLiteralText(item) ).join(","); return `(${values})`; } function assertResolvedInListValues(values) { const unresolved = values.find((item) => item.type === "VARIABLE"); if (unresolved?.type === "VARIABLE") { throw new KintoneQueryError(`\u672A\u89E3\u6C7A\u306E\u30D0\u30C3\u30C1\u5909\u6570 @${unresolved.name} \u304C\u3042\u308A\u307E\u3059`); } } function quoteIdentifier(name) { if (/^[\w$\u3000-\u9FFF]+$/u.test(name)) { return name; } return `"${name.replace(/"/g, '\\"')}"`; } function needsParens(expr) { return expr.type === "LOGICAL"; } var KintoneQueryError = class extends Error { constructor(message) { super(message); this.name = "KintoneQueryError"; } }; // src/converter/selectToKintone.ts function hasWindowColumns(columns) { return columns.some((column) => column.type === "WINDOW_COL"); } function resolveSelectMode(stmt) { if (stmt.from.subtableCode) return "FULL_SCAN"; if (stmt.joins.some((j) => j.table.subtableCode)) return "FULL_SCAN"; if (stmt.joins.length > 0) return "FULL_SCAN"; if (stmt.groupBy.length > 0) return "FULL_SCAN"; if (stmt.distinct) return "FULL_SCAN"; if (hasWindowColumns(stmt.columns)) return "FULL_SCAN"; if (stmt.columns.some( (c) => c.type === "AGGREGATE" || c.type === "ARITH_AGG_COL" || c.type === "SCALAR_SUBQUERY_COL" || c.type === "STRFUNC_COL" && hasAggregateInStringFuncExpr(c.expr) || c.type === "SCALAR_VALUE_COL" && scalarValueHasAggregate(c.expr) )) return "FULL_SCAN"; if (whereRequiresJsEval(stmt.where)) return "FULL_SCAN"; if (stmt.orderBy.some((o) => o.key.type !== "FIELD_NAME")) return "FULL_SCAN"; return "SIMPLE"; } function whereRequiresJsEval(where) { if (where === null) return false; switch (where.type) { case "BOOLEAN": return true; case "BINARY": return isFunc(where.left) || where.right.type === "ARITH_VALUE" || where.right.type === "CASE_VALUE" || where.right.type === "SUBQUERY_IN_LIST" || where.right.type === "SCALAR_SUBQUERY" || isLike(where); case "NULL_CHECK": return isFunc(where.field); case "LOGICAL": return whereRequiresJsEval(where.left) || whereRequiresJsEval(where.right); case "NOT": case "GROUP": return whereRequiresJsEval(where.expr); case "EXISTS": return true; } } function isFunc(fv) { return fv.type === "FUNC_FIELD" || fv.type === "ARITH_FIELD" || fv.type === "CASE_FIELD"; } function selectToKintoneParams(stmt) { const queryParts = []; const hasPagination = stmt.limit !== null || stmt.offset !== null; const shouldInjectDefaultOrder = hasPagination && stmt.orderBy.length === 0; if (stmt.where !== null) { queryParts.push(whereToKintone(stmt.where)); } if (stmt.orderBy.length > 0) { const orderStr = stmt.orderBy.map(convertOrderBy).join(", "); queryParts.push(`order by ${orderStr}`); } else if (shouldInjectDefaultOrder) { queryParts.push("order by $id asc"); } if (stmt.limit !== null) { queryParts.push(`limit ${stmt.limit}`); } if (stmt.offset !== null) { queryParts.push(`offset ${stmt.offset}`); } return { app: stmt.from.appId, query: queryParts.join(" "), fields: extractFields(stmt.columns), totalCount: false }; } function selectToFetchAllParams(stmt, appId) { const queryParts = []; if (stmt.where !== null && stmt.joins.length === 0 && !whereRequiresJsEval(stmt.where)) { queryParts.push(whereToKintone(stmt.where)); } return { app: appId, query: queryParts.join(" "), fields: [] // 全件取得なので全フィールドを取得する }; } function selectToFetchAllFields(stmt, targetTable) { const plan = collectRequiredFieldsByTable(stmt); const target = plan.get(targetTable); if (!target) return []; if (target.allFields) return []; const fields = new Set(target.fields); if (target.table.subtableCode) { fields.add(target.table.subtableCode); } if (fields.size === 0) fields.add("$id"); return [...fields]; } function convertOrderBy(item) { const dir = item.direction === "ASC" ? "asc" : "desc"; if (item.key.type !== "FIELD_NAME") { throw new Error("ORDER BY \u5F0F\u306F kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093\uFF08FULL_SCAN \u304C\u5FC5\u8981\u3067\u3059\uFF09"); } return `${item.key.name} ${dir}`; } function extractFields(columns) { const hasWildcard = columns.some( (c) => c.type === "WILDCARD" || c.type === "AGGREGATE" || c.type === "ARITH_AGG_COL" || c.type === "CASE_COL" || c.type === "SCALAR_SUBQUERY_COL" ); if (hasWildcard) return []; const fields = []; for (const col of columns) { if (col.type === "FIELD") { fields.push(normalizeSimpleFieldRef(col.field)); } else if (col.type === "ARITH_COL") { collectArithNode(col.expr, fields); } else if (col.type === "STRFUNC_COL") { collectStringFuncFields(col.expr, fields); } else if (col.type === "SCALAR_VALUE_COL") { collectScalarValueFields(col.expr, fields); } } return [...new Set(fields)]; } function collectArithFields(expr, out) { collectArithNode(expr.left, out); collectArithNode(expr.right, out); } function collectArithNode(node, out) { if (node.type === "FIELD_REF") out.push(normalizeSimpleFieldRef(node.field)); else if (node.type === "ARITH") collectArithFields(node, out); else if (node.type === "STRING_FUNC") collectStringFuncFields(node, out); } function normalizeSimpleFieldRef(field) { const dot = field.indexOf("."); if (dot <= 0) return field; const unqualified = field.slice(dot + 1); return unqualified || field; } function collectStringFuncFields(expr, out) { for (const arg of expr.args) { collectStringFuncArgFields(arg, out); } } function collectStringFuncArgFields(arg, out) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") { collectAggOperandFields(arg, out); return; } collectScalarValueFields(arg, out); } function collectScalarValueFields(expr, out) { if (expr.type === "FIELD") { out.push(normalizeSimpleFieldRef(expr.tableAlias ? `${expr.tableAlias}.${expr.field}` : expr.field)); return; } if (expr.type === "STRING_FUNC") { collectStringFuncFields(expr, out); return; } if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { collectScalarValueFields(expr.left, out); collectScalarValueFields(expr.right, out); return; } if (expr.type === "CASE_WHEN") { for (const branch of expr.branches) collectCaseResultScalarFields(branch.result, out); if (expr.elseResult) collectCaseResultScalarFields(expr.elseResult, out); } } function collectCaseResultScalarFields(result, out) { if (result.type === "ARRAY") return; if (result.type === "FIELD_REF" || result.type === "ARITH") { collectArithNode(result, out); return; } collectScalarValueFields(result, out); } function collectAggOperandFields(node, out) { if (node.type === "AGG_REF") { if (node.arg.type !== "WILDCARD") collectAggregateArgFields(node.arg, out); return; } if (node.type === "AGG_ARITH") { collectAggOperandFields(node.left, out); collectAggOperandFields(node.right, out); } } function collectAggregateArgFields(node, out) { if (node.type === "FIELD_REF" || node.type === "ARITH") collectArithNode(node, out); else collectScalarValueFields(node, out); } function hasAggregateInStringFuncExpr(expr) { return expr.args.some((arg) => { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") return true; return scalarValueHasAggregate(arg); }); } function scalarValueHasAggregate(expr) { if (expr.type === "STRING_FUNC") return hasAggregateInStringFuncExpr(expr); if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { return scalarValueHasAggregate(expr.left) || scalarValueHasAggregate(expr.right); } if (expr.type === "CASE_WHEN") { return expr.branches.some((b) => caseResultHasAggregate(b.result)) || expr.elseResult !== null && caseResultHasAggregate(expr.elseResult); } return false; } function caseResultHasAggregate(result) { if (result.type === "ARRAY" || result.type === "FIELD_REF" || result.type === "ARITH") return false; return scalarValueHasAggregate(result); } function collectRequiredFieldsByTable(stmt) { const physicalTables = [stmt.from, ...stmt.joins.map((j) => j.table)].filter((t) => t.cteName === null); const states = /* @__PURE__ */ new Map(); for (const table of physicalTables) { states.set(table, { table, allFields: false, fields: /* @__PURE__ */ new Set() }); } if (states.size === 0) return states; const firstPhysicalTable = physicalTables[0] ?? null; const subtableTable = physicalTables.find((t) => !!t.subtableCode) ?? null; const aliasToTable = /* @__PURE__ */ new Map(); for (const table of physicalTables) { if (table.alias) aliasToTable.set(table.alias, table); if (!table.subtableCode) { aliasToTable.set(`APP${table.appId}`, table); aliasToTable.set(`app${table.appId}`, table); } } const selectAliases = collectSelectOutputNames(stmt.columns); const markAll = (table) => { const st = states.get(table); if (!st) return; st.allFields = true; st.fields.clear(); }; const markAllPhysicalTables = () => { for (const t of physicalTables) markAll(t); }; const markAllSubtableTables = () => { for (const t of physicalTables) { if (t.subtableCode) markAll(t); } }; const addFieldToTable = (table, fieldName) => { const st = states.get(table); if (!st || st.allFields) return; if (table.subtableCode) { if (fieldName.startsWith("_p.")) { const parentField = fieldName.slice(3); if (parentField && parentField !== "*") st.fields.add(parentField); return; } if (fieldName === "_pid" || fieldName === "_rid" || fieldName === "_idx" || fieldName === "$id") { return; } return; } if (!fieldName) return; st.fields.add(fieldName); }; const addFieldName = (rawName, phase = "select") => { if (!rawName || rawName === "*") return; if (rawName === "_p.*") { markAllSubtableTables(); return; } if (rawName.endsWith(".*")) { const qualifier = rawName.slice(0, -2); if (!qualifier) { markAllPhysicalTables(); return; } if (qualifier === "_p") { markAllSubtableTables(); return; } const target = aliasToTable.get(qualifier); if (target) { markAll(target); return; } return; } if ((phase === "orderBy" || phase === "having" || phase === "groupBy") && selectAliases.has(rawName)) { return; } if ((phase === "orderBy" || phase === "having" || phase === "groupBy") && isAggregateSyntheticName(rawName)) { return; } const dot = rawName.indexOf("."); if (dot > 0) { const qualifier = rawName.slice(0, dot); const field = rawName.slice(dot + 1); if (qualifier === "_p") { if (subtableTable) addFieldToTable(subtableTable, `_p.${field}`); return; } const target = aliasToTable.get(qualifier); if (target) { addFieldToTable(target, field); return; } } if (firstPhysicalTable) addFieldToTable(firstPhysicalTable, rawName); }; const addFieldRef = (field, tableAlias, phase = "select") => { if (tableAlias) { if (tableAlias === "_p") { if (subtableTable) addFieldToTable(subtableTable, `_p.${field}`); return; } const target = aliasToTable.get(tableAlias); if (target) { addFieldToTable(target, field); return; } } addFieldName(field, phase); }; const walkArith = (node, phase = "select") => { if (node.type === "FIELD_REF") { addFieldName(node.field, phase); return; } if (node.type === "ARITH") { walkArith(node.left, phase); walkArith(node.right, phase); return; } if (node.type === "STRING_FUNC") { walkStringFunc(node, phase); return; } }; const walkAgg = (node, phase = "select") => { if (node.type === "AGG_REF") { if (node.arg.type !== "WILDCARD") walkAggregateArg(node.arg, phase); return; } if (node.type === "AGG_ARITH") { walkAgg(node.left, phase); walkAgg(node.right, phase); } }; const walkStringArg = (arg, phase = "select") => { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") { walkAgg(arg, phase); return; } walkScalar(arg, phase); }; const walkStringFunc = (expr, phase = "select") => { for (const arg of expr.args) walkStringArg(arg, phase); }; const walkScalar = (expr, phase = "select") => { if (expr.type === "FIELD") { addFieldRef(expr.field, expr.tableAlias, phase); return; } if (expr.type === "STRING_FUNC") { walkStringFunc(expr, phase); return; } if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { walkScalar(expr.left, phase); walkScalar(expr.right, phase); return; } if (expr.type === "CASE_WHEN") walkCase(expr, phase); }; const walkAggregateArg = (expr, phase = "select") => { if (expr.type === "FIELD_REF" || expr.type === "ARITH") { walkArith(expr, phase); return; } walkScalar(expr, phase); }; const walkCaseResult = (result, phase = "select") => { if (result.type === "ARRAY") return; if (result.type === "FIELD_REF" || result.type === "ARITH") { walkArith(result, phase); return; } walkScalar(result, phase); }; const walkCase = (expr, phase = "select") => { for (const b of expr.branches) { walkWhere(b.condition, phase); walkCaseResult(b.result, phase); } if (expr.elseResult) walkCaseResult(expr.elseResult, phase); }; const walkFieldValue = (fv, phase = "select") => { if (fv.type === "FIELD") { addFieldRef(fv.field, fv.tableAlias, phase); return; } if (fv.type === "FUNC_FIELD") { walkStringFunc(fv.expr, phase); return; } if (fv.type === "ARITH_FIELD") { walkArith(fv.expr, phase); return; } walkCase(fv.expr, phase); }; const walkSqlValue = (v, phase = "select") => { if (v.type === "ARITH_VALUE") { walkArith(v.expr, phase); return; } if (v.type === "CASE_VALUE") { walkCase(v.expr, phase); return; } }; const walkWhere = (where, phase = "where") => { if (!where) return; switch (where.type) { case "BINARY": walkFieldValue(where.left, phase); walkSqlValue(where.right, phase); return; case "NULL_CHECK": walkFieldValue(where.field, phase); return; case "LOGICAL": walkWhere(where.left, phase); walkWhere(where.right, phase); return; case "NOT": case "GROUP": walkWhere(where.expr, phase); return; case "EXISTS": case "BOOLEAN": return; } }; const walkGroupByKey = (k) => { if (k.type === "FIELD_NAME") { addFieldName(k.name, "groupBy"); return; } if (k.type === "ARITH_KEY") { walkArith(k.expr, "groupBy"); return; } walkStringFunc(k.expr, "groupBy"); }; const walkOrderByKey = (k, phase = "orderBy") => { if (k.type === "FIELD_NAME") { addFieldName(k.name, phase); return; } if (k.type === "ARITH_KEY") { walkArith(k.expr, phase); return; } walkStringFunc(k.expr, phase); }; for (const col of stmt.columns) { switch (col.type) { case "WILDCARD": markAllPhysicalTables(); break; case "PARENT_WILDCARD": markAllSubtableTables(); break; case "FIELD": addFieldName(col.field, "select"); break; case "LITERAL_COL": break; case "VARIABLE_COL": throw new Error(`internal error: unresolved SELECT variable @${col.name}`); case "AGGREGATE": if (col.arg.type !== "WILDCARD") walkAggregateArg(col.arg, "select"); break; case "ARITH_AGG_COL": walkAgg(col.expr, "select"); break; case "ARITH_COL": walkArith(col.expr, "select"); break; case "CASE_COL": walkCase(col.expr, "select"); break; case "STRFUNC_COL": walkStringFunc(col.expr, "select"); break; case "SCALAR_VALUE_COL": walkScalar(col.expr, "select"); break; case "SCALAR_SUBQUERY_COL": break; case "WINDOW_COL": for (const ref of col.partitionBy) addFieldRef(ref.field, ref.tableAlias, "select"); for (const item of col.orderBy) walkOrderByKey(item.key, "select"); break; } } for (const join of stmt.joins) { addFieldRef(join.on.left.field, join.on.left.tableAlias, "where"); addFieldRef(join.on.right.field, join.on.right.tableAlias, "where"); } walkWhere(stmt.where, "where"); for (const gk of stmt.groupBy) walkGroupByKey(gk); walkWhere(stmt.having, "having"); for (const ob of stmt.orderBy) walkOrderByKey(ob.key); return states; } function collectSelectOutputNames(columns) { const names = /* @__PURE__ */ new Set(); for (const col of columns) { if (col.type === "FIELD" && col.alias) { names.add(col.alias); continue; } if (col.type === "LITERAL_COL") { names.add(col.alias ?? `'${col.value}'`); continue; } if (col.type === "AGGREGATE") { if (col.alias) names.add(col.alias); else names.add(aggregateSyntheticName(col.func, col.distinct, col.arg)); continue; } if (col.type === "ARITH_AGG_COL") { if (col.alias) names.add(col.alias); continue; } if (col.type === "ARITH_COL") { if (col.alias) names.add(col.alias); continue; } if (col.type === "CASE_COL") { names.add(col.alias ?? "case"); continue; } if (col.type === "STRFUNC_COL") { if (col.alias) names.add(col.alias); continue; } if (col.type === "SCALAR_VALUE_COL") { if (col.alias) names.add(col.alias); continue; } if (col.type === "SCALAR_SUBQUERY_COL") { names.add(col.alias ?? "(subquery)"); continue; } if (col.type === "WINDOW_COL") { names.add(col.alias); } } return names; } function isAggregateSyntheticName(name) { return /^(COUNT|SUM|AVG|MAX|MIN|GROUP_CONCAT|STDDEV_POP|STDDEV_SAMP|VAR_POP|VAR_SAMP|MEDIAN|MODE)\(/i.test(name); } // src/core/cteInlining.ts init_define_KSQL_DOCS(); function canInlineSingleCte(stmt) { if (stmt.ctes.length !== 1) return false; const cteDef = stmt.ctes[0]; if (cteDef.query.type !== "SELECT" || resolveSelectMode(cteDef.query) !== "SIMPLE") return false; if (!cteDef.query.columns.every( (column) => column.type === "WILDCARD" || column.type === "FIELD" && (column.alias === null || column.alias === column.field) )) return false; const finalQuery = stmt.query; if (finalQuery.type !== "SELECT") return false; if (finalQuery.from.cteName !== cteDef.name || finalQuery.joins.length > 0) return false; if (finalQuery.groupBy.length > 0 || finalQuery.distinct) return false; return !finalQuery.columns.some( (column) => column.type === "AGGREGATE" || column.type === "ARITH_AGG_COL" ); } function buildInlinedQuery(stmt) { const cteBody = stmt.ctes[0].query; const final = stmt.query; const finalWhere = stripCteAlias(final.where, final.from.alias); const where = cteBody.where === null ? finalWhere : finalWhere === null ? cteBody.where : { type: "LOGICAL", op: "AND", left: cteBody.where, right: finalWhere }; const columns = final.columns.every((column) => column.type === "WILDCARD") ? cteBody.columns : final.columns; return { type: "SELECT", from: cteBody.from, joins: [], columns, where, groupBy: [], having: null, orderMode: "CANONICAL", orderBy: final.orderBy.length > 0 ? final.orderBy : cteBody.orderBy, limit: final.limit ?? cteBody.limit, offset: final.offset ?? cteBody.offset, distinct: false }; } function stripCteAlias(where, alias) { if (where === null || alias === null) return where; switch (where.type) { case "BINARY": return { ...where, left: stripCteAliasFromFieldValue(where.left, alias) }; case "NULL_CHECK": return { ...where, field: stripCteAliasFromFieldValue(where.field, alias) }; case "LOGICAL": return { ...where, left: stripCteAlias(where.left, alias), right: stripCteAlias(where.right, alias) }; case "NOT": case "GROUP": return { ...where, expr: stripCteAlias(where.expr, alias) }; case "EXISTS": case "BOOLEAN": return where; } } function stripCteAliasFromFieldValue(value, alias) { if (value.type === "FIELD" && value.tableAlias === alias) { return { ...value, tableAlias: null }; } return value; } // src/core/optimization/klikePushdownPlan.ts init_define_KSQL_DOCS(); // src/core/optimization/wherePredicatePushdown.ts init_define_KSQL_DOCS(); function extractSafePushdownLeaves(where, options = {}) { return extractAndLeaves(where, (expr) => isSafeComparison(expr, options)); } function extractTypedPushdownCandidates(where, options = {}) { return extractAndLeaves( where, (expr) => isNumericCandidate(expr, options) || isSelectionInCandidate(expr, options) ); } function extractAndLeaves(where, accept) { switch (where.type) { case "BINARY": return accept(where) ? where : null; case "LOGICAL": if (where.op !== "AND") return null; { const left = extractAndLeaves(where.left, accept); const right = extractAndLeaves(where.right, accept); if (left && right) return { ...where, left, right }; return left ?? right ?? null; } case "GROUP": return extractAndLeaves(where.expr, accept); case "NULL_CHECK": case "NOT": case "EXISTS": case "BOOLEAN": return null; } } function isSafeComparison(expr, options) { if (isKlikeComparison(expr, options)) return true; if (isSafeIdComparison(expr, options)) return true; if (isNumericCandidate(expr, options)) { return options.fieldTypes?.get(expr.left.field) === "NUMBER"; } return isSelectionInComparison(expr, options); } function isKlikeComparison(expr, options) { if (options.allowKlike === false) return false; if (expr.op !== "KLIKE" && expr.op !== "NOT_KLIKE") return false; if (expr.left.type !== "FIELD" || !isTargetField(expr.left, options)) return false; return expr.right.type === "STRING" || options.allowUnresolvedKlikeVariables === true && expr.right.type === "VARIABLE"; } var SELECTION_IN_FIELD_TYPES = /* @__PURE__ */ new Set([ "DROP_DOWN", "RADIO_BUTTON", "CHECK_BOX", "MULTI_SELECT", "STATUS" ]); function isSelectionInComparison(expr, options) { if (!isSelectionInCandidate(expr, options)) return false; if (expr.left.type !== "FIELD" || expr.right.type !== "IN_LIST") return false; const fieldType = options.fieldTypes?.get(expr.left.field); if (fieldType === void 0 || !SELECTION_IN_FIELD_TYPES.has(fieldType)) return false; const validOptions = options.fieldOptions?.get(expr.left.field); if (validOptions === void 0) return false; return expr.right.values.every( (value) => value.type === "STRING" && value.value !== "" && validOptions.has(value.value) ); } function isSafeIdComparison(expr, options) { if (!isTargetIdField(expr.left, options)) return false; if (expr.right.type !== "NUMBER") return false; return expr.op === "=" || expr.op === ">" || expr.op === "<" || expr.op === ">=" || expr.op === "<="; } function isTargetIdField(field, options) { if (field.type !== "FIELD" || field.field !== "$id") return false; const targetAlias = options.tableAlias ?? null; if (field.tableAlias === targetAlias) return true; return options.allowUnqualifiedFields === true && field.tableAlias === null; } function isNumericCandidate(expr, options) { if (expr.left.type !== "FIELD" || expr.left.field === "$id") return false; if (!isTargetField(expr.left, options)) return false; if (expr.right.type !== "NUMBER") return false; if (expr.op === "=") return true; return (expr.op === "<" || expr.op === ">") && /^[+-]?\d+$/.test(numberLiteralText(expr.right)) && Number.isSafeInteger(expr.right.value); } function isSelectionInCandidate(expr, options) { if (expr.left.type !== "FIELD" || expr.left.field === "$id") return false; if (!isTargetField(expr.left, options)) return false; if (expr.op !== "IN" && expr.op !== "NOT_IN") return false; if (expr.right.type !== "IN_LIST" || expr.right.values.length === 0) return false; return expr.right.values.every((value) => value.type === "STRING" && value.value !== ""); } function isTargetField(field, options) { const targetAlias = options.tableAlias ?? null; if (field.tableAlias === targetAlias) return true; return options.allowUnqualifiedFields === true && field.tableAlias === null; } // src/core/optimization/klikePushdownPlan.ts function buildSingleTableKlikePushdownPlan(where, options = {}) { const condition = where !== null && options.extractCondition !== false ? extractSafePushdownLeaves(where, options) : null; const appliedKlikes = /* @__PURE__ */ new Set(); collectKlikes(condition, appliedKlikes); const allKlikes = /* @__PURE__ */ new Set(); collectKlikes(where, allKlikes); return { condition, appliedKlikes, allKlikes: [...allKlikes] }; } function buildKlikePushdownPlan(stmt, options = {}) { const joinsAreSafeForKlike = stmt.joins.every((join) => join.type === "INNER"); const common = { allowKlike: joinsAreSafeForKlike, allowUnresolvedKlikeVariables: options.allowUnresolvedVariables }; const mainIsPhysical = !stmt.from.subtableCode && stmt.from.cteName === null; const mainHasUsableAlias = stmt.joins.length === 0 || stmt.from.alias !== null; const mainPlan = buildSingleTableKlikePushdownPlan(stmt.where, { ...common, extractCondition: mainIsPhysical && mainHasUsableAlias, tableAlias: stmt.from.alias ?? void 0, allowUnqualifiedFields: stmt.joins.length === 0, fieldTypes: options.fieldTypesByApp?.get(stmt.from.appId), fieldOptions: options.fieldOptionsByApp?.get(stmt.from.appId) }); const mainCondition = mainPlan.condition; const joinConditions = /* @__PURE__ */ new Map(); if (stmt.where !== null) { for (const join of stmt.joins) { if (!join.table.alias || join.table.subtableCode || join.table.cteName !== null) continue; const condition = extractSafePushdownLeaves(stmt.where, { ...common, tableAlias: join.table.alias, fieldTypes: options.fieldTypesByApp?.get(join.table.appId), fieldOptions: options.fieldOptionsByApp?.get(join.table.appId) }); if (condition !== null) joinConditions.set(join.table.alias, condition); } } const appliedKlikes = new Set(mainPlan.appliedKlikes); for (const condition of joinConditions.values()) collectKlikes(condition, appliedKlikes); return { mainCondition, joinConditions, appliedKlikes, allKlikes: mainPlan.allKlikes }; } function unappliedKlikes(plan) { return plan.allKlikes.filter((expr) => !plan.appliedKlikes.has(expr)); } function collectKlikes(where, out) { if (where === null) return; if (isKlike(where)) { out.add(where); return; } switch (where.type) { case "LOGICAL": collectKlikes(where.left, out); collectKlikes(where.right, out); return; case "NOT": case "GROUP": collectKlikes(where.expr, out); return; case "BINARY": case "NULL_CHECK": case "EXISTS": case "BOOLEAN": return; } } // src/core/klikeValidation.ts var KlikeValidationError = class extends Error { constructor(message) { super(`ArgumentError: ${message}`); this.name = "ArgumentError"; } }; function validateKlikeStatement(stmt) { validateStatement(stmt); } function validateKlikePushdownPlan(plan) { if (unappliedKlikes(plan).length > 0) { throw new KlikeValidationError( "FULL_SCAN \u306E KLIKE / NOT KLIKE \u3092\u5B89\u5168\u306B\u62BC\u3057\u4E0B\u3052\u3089\u308C\u307E\u305B\u3093\u3002OR / NOT \u914D\u4E0B\u3001CTE\u30FB\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3001LEFT / RIGHT JOIN \u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044" ); } } function validateStatement(stmt) { switch (stmt.type) { case "SELECT": validateSelect(stmt); return; case "UNION": validateUnion(stmt); return; case "WITH": validateWith(stmt); return; case "EXPLAIN": validateStatement(stmt.query); return; case "CREATE_TEMP_TABLE": validateSelectLike(stmt.query); return; case "SET_VARIABLE": case "DECLARE_VARIABLE": case "ASSERT": validateNestedSelects(stmt); return; case "UPDATE": if (stmt.applyBlocks?.length && !isSinglePositiveRecordIdWhere(stmt.where) && whereHasKlike(stmt.where)) { validateKlikeWhereExpressions(stmt.where); validateNestedSelects(stmt); return; } if (containsKlike(stmt) && stmt.subtableCode) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306E WHERE \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } if (!stmt.applyBlocks?.length && !stmt.subtableCode && whereHasKlike(stmt.where) && !containsKlikeOutsideWhereAndNestedSelects(stmt, stmt.where)) { validateKlikeWhereExpressions(stmt.where); validateNestedSelects(stmt); return; } if (containsKlike(stmt)) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F\u901A\u5E38\u89AA UPDATE \u306E WHERE\u3001\u307E\u305F\u306F APPLY \u8907\u6570\u89AA UPDATE \u306E\u5B89\u5168\u306A\u89AA WHERE \u3060\u3051\u3067\u4F7F\u7528\u3067\u304D\u307E\u3059" ); } return; case "DELETE": if (containsKlike(stmt) && stmt.subtableCode) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB DELETE \u306E WHERE \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } if (!stmt.subtableCode && whereHasKlike(stmt.where)) { validateKlikeWhereExpressions(stmt.where); validateNestedSelects(stmt); return; } if (containsKlike(stmt)) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F\u901A\u5E38\u89AA DELETE \u306E WHERE \u3060\u3051\u3067\u4F7F\u7528\u3067\u304D\u307E\u3059" ); } return; case "INSERT": case "INSERT_SELECT": if (containsKlike(stmt)) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F INSERT / INSERT SELECT \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } return; case "UPSERT": case "UPSERT_SELECT": if (containsKlike(stmt)) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F UPSERT / UPSERT SELECT \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } return; case "REORDER": if (containsKlike(stmt)) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB REORDER \u306E WHERE \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } return; case "VALIDATE": if (containsKlike(stmt)) { throw new KlikeValidationError("KLIKE / NOT KLIKE \u306F VALIDATE \u306E WHERE / CHECK \u3067\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"); } return; case "SHOW_APPS": case "DESCRIBE": case "DROP_TEMP_TABLE": return; } } function validateKlikeWhereExpressions(where) { walkWithoutNestedSelects(where, (expr) => { if (!isKlike(expr)) return; const right = expr.right; if (right.type !== "STRING" && right.type !== "VARIABLE") { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306E\u53F3\u8FBA\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u307E\u305F\u306F\u6587\u5B57\u5217\u30D0\u30C3\u30C1\u5909\u6570\u304C\u5FC5\u8981\u3067\u3059" ); } if (right.type === "STRING" && right.value.includes("%")) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306E\u691C\u7D22\u8A9E\u306B % \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002SQL \u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u691C\u7D22\u306B\u306F LIKE \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044" ); } }); } function validateSelectLike(query) { if (query.type === "SELECT") validateSelect(query); else if (query.type === "UNION") validateUnion(query); else validateWith(query); } function validateUnion(stmt) { validateSelectLike(stmt.left); validateSelect(stmt.right); } function validateWith(stmt) { if (canInlineSingleCte(stmt)) { validateSelect(buildInlinedQuery(stmt)); return; } for (const cte of stmt.ctes) { if (cte.query.type === "SELECT") validateSelect(cte.query); else if (cte.query.type === "UNION") validateUnion(cte.query); } validateSelectLike(stmt.query); } function validateSelect(stmt) { validateOwnKlikeExpressions(stmt); if (whereHasKlike(stmt.where)) { const directKintoneSimple = resolveSelectMode(stmt) === "SIMPLE" && stmt.from.cteName === null && stmt.joins.every((join) => join.table.cteName === null); if (!directKintoneSimple) { const plan = buildKlikePushdownPlan(stmt, { allowUnresolvedVariables: true }); if (unappliedKlikes(plan).length === 0) { validateNestedSelects(stmt); return; } throw new KlikeValidationError( "FULL_SCAN \u306E KLIKE / NOT KLIKE \u306F\u3001\u7269\u7406\u30C6\u30FC\u30D6\u30EB\u306B\u5BFE\u3059\u308B AND \u30EA\u30FC\u30D5\u3068\u3057\u3066\u5FC5\u305A\u62BC\u3057\u4E0B\u3052\u3089\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002OR / NOT \u914D\u4E0B\u3001CTE\u30FB\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3001LEFT / RIGHT JOIN \u3067\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } } validateNestedSelects(stmt); } function validateOwnKlikeExpressions(stmt) { walkWithoutNestedSelects(stmt, (where) => { if (!isKlike(where)) return; if (!isDescendantOf(stmt.where, where)) { throw new KlikeValidationError("KLIKE / NOT KLIKE \u306F SELECT \u306E WHERE \u53E5\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059"); } const right = where.right; if (right.type !== "STRING" && right.type !== "VARIABLE") { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306E\u53F3\u8FBA\u306B\u306F\u6587\u5B57\u5217\u30EA\u30C6\u30E9\u30EB\u307E\u305F\u306F\u6587\u5B57\u5217\u30D0\u30C3\u30C1\u5909\u6570\u304C\u5FC5\u8981\u3067\u3059" ); } if (right.type === "STRING" && right.value.includes("%")) { throw new KlikeValidationError( "KLIKE / NOT KLIKE \u306E\u691C\u7D22\u8A9E\u306B % \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002SQL \u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u691C\u7D22\u306B\u306F LIKE \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044" ); } }); } function validateNestedSelects(node) { walkObjects(node, (obj) => { if (obj.type === "SELECT") validateSelect(obj); }, true); } function containsKlike(node) { let found = false; walkObjects(node, (obj) => { if (obj.type === "BINARY" && (obj.op === "KLIKE" || obj.op === "NOT_KLIKE")) found = true; }); return found; } function containsKlikeOutsideWhereAndNestedSelects(node, allowedWhere) { let found = false; const visit = (value) => { if (found || value === allowedWhere || value === null || typeof value !== "object") return; if (Array.isArray(value)) { for (const item of value) visit(item); return; } const obj = value; if (obj.type === "SELECT") return; if (obj.type === "BINARY" && (obj.op === "KLIKE" || obj.op === "NOT_KLIKE")) { found = true; return; } for (const child of Object.values(obj)) visit(child); }; visit(node); return found; } function isDescendantOf(root, target) { if (root === null) return false; if (root === target) return true; switch (root.type) { case "LOGICAL": return isDescendantOf(root.left, target) || isDescendantOf(root.right, target); case "NOT": case "GROUP": return isDescendantOf(root.expr, target); case "BINARY": case "NULL_CHECK": case "EXISTS": return false; case "BOOLEAN": return false; } } function walkWithoutNestedSelects(node, visitWhere) { if (Array.isArray(node)) { for (const value of node) walkWithoutNestedSelects(value, visitWhere); return; } if (node === null || typeof node !== "object") return; const obj = node; if (obj.type === "BINARY" || obj.type === "NULL_CHECK" || obj.type === "LOGICAL" || obj.type === "NOT" || obj.type === "GROUP" || obj.type === "EXISTS") { visitWhere(obj); } for (const value of Object.values(obj)) { if (value !== node && isSelectObject(value)) continue; walkWithoutNestedSelects(value, visitWhere); } } function walkObjects(node, visit, skipRoot = false) { if (Array.isArray(node)) { for (const value of node) walkObjects(value, visit); return; } if (node === null || typeof node !== "object") return; const obj = node; if (!skipRoot) visit(obj); for (const value of Object.values(obj)) walkObjects(value, visit); } function isSelectObject(value) { return value !== null && typeof value === "object" && value.type === "SELECT"; } // src/core/batch.ts var MAX_TEMP_TABLES = 16; var MAX_BATCH_VARIABLES = 64; var BatchAnalysisError = class extends Error { constructor(message, statementIndex) { super(message); this.statementIndex = statementIndex; } }; function collectRefs(node, tempRefs, appIds) { if (Array.isArray(node)) { for (const v of node) collectRefs(v, tempRefs, appIds); return; } if (node !== null && typeof node === "object") { const obj = node; const cte = obj["cteName"]; if (typeof cte === "string" && cte.startsWith("#")) tempRefs.add(cte); const appId = obj["appId"]; if (typeof appId === "number" && appId > 0) appIds.add(appId); for (const v of Object.values(obj)) collectRefs(v, tempRefs, appIds); } } function collectVariableRefs(node, refs) { if (Array.isArray(node)) { for (const v of node) collectVariableRefs(v, refs); return; } if (node !== null && typeof node === "object") { const obj = node; const type = obj["type"]; if ((type === "VARIABLE" || type === "VARIABLE_COL" || type === "VARIABLE_IN_LIST") && typeof obj["name"] === "string") { refs.push({ name: obj["name"], kind: type === "VARIABLE" ? "scalar" : type === "VARIABLE_COL" ? "select-column" : "array-in-list" }); return; } for (const v of Object.values(obj)) collectVariableRefs(v, refs); } } function analyzeBatch(statements) { if (statements.length === 0) { throw new BatchAnalysisError("ArgumentError: SQL is empty.", 0); } statements.forEach((stmt, index) => { try { assertApplyScope("phase15b", stmt); validateKlikeStatement(stmt); } catch (error51) { if (error51 instanceof KlikeValidationError) { throw new BatchAnalysisError(error51.message, index); } if (error51 instanceof Error && /^(UnsupportedError|ArgumentError): APPLY /.test(error51.message)) { throw new BatchAnalysisError(error51.message, index); } throw error51; } }); if (statements.length === 1) { const t = statements[0].type; if (t === "SET_VARIABLE" || t === "DECLARE_VARIABLE") { const verb = t === "SET_VARIABLE" ? "SET" : "DECLARE"; throw new BatchAnalysisError(`ArgumentError: ${verb} variable requires a batch.`, 0); } if (t === "CREATE_TEMP_TABLE" || t === "DROP_TEMP_TABLE") { const verb = t === "CREATE_TEMP_TABLE" ? "CREATE TEMP TABLE" : "DROP TEMP TABLE"; throw new BatchAnalysisError( `ArgumentError: ${verb} requires a batch (temp tables are batch-scoped).`, 0 ); } } const defined = /* @__PURE__ */ new Map(); const validationSchemas = /* @__PURE__ */ new Map(); const createdOrder = []; const results = []; const variableDefs = /* @__PURE__ */ new Map(); const variableOrder = []; statements.forEach((stmt, index) => { const validationTable = stmt.type === "VALIDATE" && stmt.errorTable ? stmt.errorTable : "validationErrorTable" in stmt && stmt.validationErrorTable ? stmt.validationErrorTable : "onErrorSkip" in stmt && stmt.onErrorSkip ? stmt.errorTable ?? null : null; if (statements.length === 1 && validationTable) { const message = stmt.type === "VALIDATE" ? "ArgumentError: VALIDATE INTO requires a batch." : "onErrorSkip" in stmt && stmt.onErrorSkip ? "ArgumentError: ON ERROR SKIP requires a batch." : "ArgumentError: VALIDATE ONLY INTO requires a batch."; throw new BatchAnalysisError(message, index); } const statementType = getStatementType(stmt); const created = []; const dropped = []; const refs = /* @__PURE__ */ new Set(); const stmtAppIds = /* @__PURE__ */ new Set(); const dependsOn = /* @__PURE__ */ new Set(); const variableRefs = []; collectVariableRefs(stmt, variableRefs); const referencedThisStatement = /* @__PURE__ */ new Set(); for (const use of variableRefs) { const def = variableDefs.get(use.name); if (def === void 0) { throw new BatchAnalysisError( `ParseError: variable @${use.name} is not defined before statement ${index + 1}.`, index ); } if (def.kind === "scalar" && use.kind === "array-in-list") { throw new BatchAnalysisError( `ParseError: scalar variable @${use.name} cannot be used as IN @${use.name}; use IN (@${use.name}) instead.`, index ); } if (def.kind === "array" && use.kind !== "array-in-list") { throw new BatchAnalysisError( `ParseError: array variable @${use.name} can only be used as IN @${use.name}.`, index ); } if (!referencedThisStatement.has(use.name)) { def.referencedBy.push(index); referencedThisStatement.add(use.name); } } if (stmt.type === "SET_VARIABLE" || stmt.type === "DECLARE_VARIABLE") { if (variableDefs.has(stmt.name)) { throw new BatchAnalysisError(`ParseError: variable @${stmt.name} is already defined.`, index); } variableDefs.set(stmt.name, { index, kind: stmt.type === "SET_VARIABLE" && stmt.expr.type === "ARRAY" ? "array" : "scalar", referencedBy: [] }); variableOrder.push(stmt.name); if (variableOrder.length > MAX_BATCH_VARIABLES) { throw new BatchAnalysisError( `ParseError: batch exceeds ${MAX_BATCH_VARIABLES} variables.`, index ); } } if (stmt.type === "CREATE_TEMP_TABLE") { collectRefs(stmt.query, refs, stmtAppIds); } else if (stmt.type === "DROP_TEMP_TABLE") { } else { collectRefs(stmt, refs, stmtAppIds); } let tempOnlySource = false; if (stmt.type === "INSERT_SELECT" || stmt.type === "UPSERT_SELECT") { const srcTemp = /* @__PURE__ */ new Set(); const srcApps = /* @__PURE__ */ new Set(); collectRefs(stmt.select, srcTemp, srcApps); tempOnlySource = srcTemp.size > 0 && srcApps.size === 0; } for (const name of refs) { const at = defined.get(name); if (at === void 0) { throw new BatchAnalysisError( `ParseError: temp table ${name} is not defined in this batch.`, index ); } dependsOn.add(at); } if (validationTable) { const payloadFields = stmt.type === "VALIDATE" ? stmt.summary ? ["$id", "$err_subtable", "$err_field", "$err_code", "$err_count"] : ["$id", "$err_field", "$err_code", "$err_message", "$err_value", "$err_subtable", "$err_subrow", "$err_subrow_id", "$err_count"] : stmt.type === "IMPORT" && stmt.targets?.some((target) => target.kind === "SUBTABLE") ? [...new Set(stmt.targets.flatMap((target) => target.kind === "FIELD" ? [target.field] : target.children)), "$err_subtable", "$err_subrow", "$err_source_row"] : stmt.type === "UPDATE" ? ["$id", ...stmt.assignments.map((a) => a.field)] : "fields" in stmt ? stmt.fields : []; const signature = JSON.stringify(payloadFields); const at = defined.get(validationTable); if (at === void 0) { defined.set(validationTable, index); validationSchemas.set(validationTable, signature); createdOrder.push(validationTable); created.push(validationTable); if (defined.size > MAX_TEMP_TABLES) { throw new BatchAnalysisError(`ParseError: batch exceeds ${MAX_TEMP_TABLES} temp tables.`, index); } } else { if (validationSchemas.get(validationTable) !== signature) { throw new BatchAnalysisError( `ParseError: validation error table ${validationTable} has a different payload schema.`, index ); } dependsOn.add(at); } } if (stmt.type === "CREATE_TEMP_TABLE") { if (defined.has(stmt.name)) { throw new BatchAnalysisError( `ParseError: temp table ${stmt.name} is already defined.`, index ); } defined.set(stmt.name, index); createdOrder.push(stmt.name); created.push(stmt.name); if (defined.size > MAX_TEMP_TABLES) { throw new BatchAnalysisError( `ParseError: batch exceeds ${MAX_TEMP_TABLES} temp tables.`, index ); } } if (stmt.type === "DROP_TEMP_TABLE") { const at = defined.get(stmt.name); if (at === void 0) { throw new BatchAnalysisError( `ParseError: temp table ${stmt.name} is not defined in this batch.`, index ); } dependsOn.add(at); dropped.push(stmt.name); defined.delete(stmt.name); } results.push({ index, statementType, isDml: writesKintone(stmt), isReadOnly: isReadOnlyStatement(stmt), hasWhere: hasWhereClause(stmt), insertValuesCount: getInsertValuesCount(stmt), appIds: [...stmtAppIds].sort((a, b) => a - b), tempTablesCreated: created, tempTablesReferenced: [...refs], tempTablesDropped: dropped, dependsOn: [...dependsOn].sort((a, b) => a - b), tempOnlySource, targetAppId: isDmlType(statementType) && typeof stmt.appId === "number" ? stmt.appId : null, isUpdateFrom: stmt.type === "UPDATE" && stmt.from != null, isValidationOnly: "validateOnly" in stmt && stmt.validateOnly === true, isOnErrorSkip: "onErrorSkip" in stmt && stmt.onErrorSkip === true, requiresCompleteInput: requiresCompleteInput(stmt) }); }); const containsDml = results.some((r) => r.isDml); const containsValidationOnly = results.some((r) => r.isValidationOnly); const needsCompleteInput = results.some((r) => r.requiresCompleteInput); const variables = variableOrder.map((name) => ({ name, kind: variableDefs.get(name).kind, referencedBy: [...variableDefs.get(name).referencedBy] })); return { statementCount: statements.length, isReadOnlyBatch: !containsDml && results.every((r) => r.isReadOnly), containsDml, containsValidationOnly, requiresCompleteInput: needsCompleteInput, tempTables: createdOrder, variables, warnings: variables.filter((v) => v.referencedBy.length === 0).map((v) => `variable @${v.name} is never used.`), statements: results }; } // src/core/applyPatchPlanner.ts init_define_KSQL_DOCS(); // src/converter/dmlToKintone.ts init_define_KSQL_DOCS(); // src/core/dmlCustomCheck.ts init_define_KSQL_DOCS(); // src/engine/evalWhere.ts init_define_KSQL_DOCS(); // src/engine/evalFunc.ts init_define_KSQL_DOCS(); // src/core/scalarCompare.ts init_define_KSQL_DOCS(); // src/core/fieldSemantics.ts init_define_KSQL_DOCS(); var STRING_FIELD_TYPES = /* @__PURE__ */ new Set([ "SINGLE_LINE_TEXT", "MULTI_LINE_TEXT", "RICH_TEXT", "LINK", "DATE", "TIME", "DATETIME", "CREATED_TIME", "UPDATED_TIME", "CREATOR", "MODIFIER" ]); var OPTION_FIELD_TYPES = /* @__PURE__ */ new Set([ "DROP_DOWN", "RADIO_BUTTON", "CHECK_BOX", "MULTI_SELECT", "STATUS" ]); function resolveFieldSemantics(source) { let compareMode; if (source.fieldType === "RECORD_NUMBER" || source.fieldType === "__ID__") { compareMode = "recordNumber"; } else if (source.fieldType === "NUMBER") { compareMode = "number"; } else if (source.fieldType === "CALC") { compareMode = source.sortKind === "number" ? "number" : "string"; } else if (OPTION_FIELD_TYPES.has(source.fieldType)) { compareMode = "option"; } else if (STRING_FIELD_TYPES.has(source.fieldType)) { compareMode = "string"; } else { compareMode = "unsupported"; } const optionOrder = source.optionOrder ? new Map(Object.entries(source.optionOrder)) : void 0; return { fieldType: source.fieldType, compareMode, inSubtable: source.inSubtable === true, requiresCollectionOperators: source.inSubtable === true || source.requiresCollectionOperators === true, ...optionOrder && optionOrder.size > 0 ? { optionOrder } : {} }; } function syntheticSemantics(compareMode, fieldType = compareMode === "number" ? "KSQL_NUMBER" : "KSQL_STRING") { return { fieldType, compareMode, inSubtable: false, requiresCollectionOperators: false }; } function withFieldSemanticSource(semantics, appId, fieldCode) { return { ...semantics, source: { appId, fieldCode } }; } function fieldSemanticsEqual(left, right) { if (left === right) return true; if (!left || !right) return false; if (left.fieldType !== right.fieldType || left.compareMode !== right.compareMode || left.inSubtable !== right.inSubtable || left.requiresCollectionOperators !== right.requiresCollectionOperators) return false; if (left.source?.appId !== right.source?.appId || left.source?.fieldCode !== right.source?.fieldCode) return false; const a = left.optionOrder; const b = right.optionOrder; if (a === b) return true; if (!a || !b || a.size !== b.size) return false; for (const [key, value] of a) { if (b.get(key) !== value) return false; } return true; } // src/core/scalarCompare.ts function compareCodePointStrings(left, right) { const a = left[Symbol.iterator](); const b = right[Symbol.iterator](); while (true) { const av = a.next(); const bv = b.next(); if (av.done || bv.done) { if (av.done && bv.done) return 0; return av.done ? -1 : 1; } const ac = av.value.codePointAt(0) ?? 0; const bc = bv.value.codePointAt(0) ?? 0; if (ac < bc) return -1; if (ac > bc) return 1; } } function triCompare(left, right) { return left < right ? -1 : left > right ? 1 : 0; } function numberKey(value) { if (value === "") return { band: 0 }; const decimal = parseExactDecimal(value); if (decimal !== null) return { band: 2, value: decimal }; const numeric = Number(value); if (numeric === Number.NEGATIVE_INFINITY) return { band: 1 }; if (numeric === Number.POSITIVE_INFINITY) return { band: 3 }; if (value === "NaN") return { band: 4 }; return { band: 5, value }; } function compareNumbers(left, right) { const a = numberKey(left); const b = numberKey(right); if (a.band !== b.band) return a.band < b.band ? -1 : 1; if (a.band === 2 && b.band === 2) return compareExactDecimal(a.value, b.value); if (a.band === 5 && b.band === 5) return compareCodePointStrings(a.value, b.value); return 0; } function recordNumberKey(value, allowPrefix) { if (value === "") return { empty: true, normalizedId: "", display: value }; const match = /^\d+$/.test(value) ? value : allowPrefix ? /-(\d+)$/.exec(value)?.[1] : void 0; if (match === void 0) { throw new Error(`ArgumentError: invalid ${allowPrefix ? "RECORD_NUMBER" : "$id"} value: ${value}`); } return { empty: false, normalizedId: match.replace(/^0+(?=\d)/, ""), display: value }; } function compareRecordNumbers(left, right, allowPrefix) { const a = recordNumberKey(left, allowPrefix); const b = recordNumberKey(right, allowPrefix); if (a.empty || b.empty) return a.empty === b.empty ? 0 : a.empty ? -1 : 1; if (a.normalizedId.length !== b.normalizedId.length) { return a.normalizedId.length < b.normalizedId.length ? -1 : 1; } const idCmp = compareCodePointStrings(a.normalizedId, b.normalizedId); return idCmp !== 0 ? idCmp : compareCodePointStrings(a.display, b.display); } function parseOptionValues(value, fieldType) { if (value === "") return []; if (fieldType !== "CHECK_BOX" && fieldType !== "MULTI_SELECT") return [value]; try { const parsed = JSON.parse(value); return Array.isArray(parsed) ? parsed.map((item) => String(item ?? "")) : [value]; } catch { return [value]; } } function optionVector(value, semantics) { const order = semantics.optionOrder ?? /* @__PURE__ */ new Map(); const unique = [...new Set(parseOptionValues(value, semantics.fieldType))]; const vector = unique.map((label) => { const rank = order.get(label); return rank === void 0 ? { knownBand: 1, rank: 0, label } : { knownBand: 0, rank, label }; }); vector.sort(compareOptionElement); return vector; } function compareOptionElement(left, right) { if (left.knownBand !== right.knownBand) return left.knownBand < right.knownBand ? -1 : 1; if (left.rank !== right.rank) return left.rank < right.rank ? -1 : 1; return compareCodePointStrings(left.label, right.label); } function compareOptions(left, right, semantics) { const a = optionVector(left, semantics); const b = optionVector(right, semantics); const length = Math.min(a.length, b.length); for (let index = 0; index < length; index++) { const cmp = compareOptionElement(a[index], b[index]); if (cmp !== 0) return cmp; } return a.length < b.length ? -1 : a.length > b.length ? 1 : 0; } function compareCanonicalValues(left, right, semantics) { switch (semantics.compareMode) { case "string": return compareCodePointStrings(left, right); case "number": return compareNumbers(left, right); case "recordNumber": return compareRecordNumbers(left, right, semantics.fieldType === "RECORD_NUMBER"); case "option": return compareOptions(left, right, semantics); case "unsupported": throw new Error(`ArgumentError: values of type ${semantics.fieldType} cannot be compared.`); } } function compareScalarValues(op, left, right, semantics = syntheticSemantics("string")) { const cmp = compareCanonicalValues(left, right, semantics); switch (op) { case "=": return cmp === 0; case "!=": case "<>": return cmp !== 0; case ">": return cmp > 0; case "<": return cmp < 0; case ">=": return cmp >= 0; case "<=": return cmp <= 0; } } function selectScalarExtreme(values, extreme) { if (extreme === "least" && values.includes("")) return ""; const candidates = extreme === "greatest" ? values.filter((value) => value !== "") : [...values]; if (candidates.length === 0) return ""; const numeric = candidates.every((value) => !Number.isNaN(Number(value))); const compare = (left, right) => { if (numeric) { const leftDecimal = parseExactDecimal(left); const rightDecimal = parseExactDecimal(right); const numericCmp = leftDecimal !== null && rightDecimal !== null ? compareExactDecimal(leftDecimal, rightDecimal) : triCompare(Number(left), Number(right)); if (numericCmp !== 0) return numericCmp; } return compareCodePointStrings(left, right); }; return candidates.reduce((best, candidate) => { const cmp = compare(candidate, best); return extreme === "greatest" ? cmp > 0 ? candidate : best : cmp < 0 ? candidate : best; }); } // src/engine/evalFunc.ts function evalArithExpr(expr, row) { if (expr.type === "NUMBER") return expr.value; if (expr.type === "FIELD_REF") return Number(resolveFieldRef(row, expr.field)); if (expr.type === "STRING_FUNC") return Number(evalStringFunc(expr, row)); const l = evalArithExpr(expr.left, row); const r = evalArithExpr(expr.right, row); switch (expr.op) { case "+": return l + r; case "-": return l - r; case "*": return l * r; case "/": return r !== 0 ? l / r : NaN; case "%": return r !== 0 ? l % r : NaN; } } function evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2) { switch (expr.type) { case "STRING": return expr.value; case "NUMBER": return expr.value; case "FIELD": return resolveFieldRef(row, expr.tableAlias ? `${expr.tableAlias}.${expr.field}` : expr.field); case "VARIABLE": throw new Error(`ArgumentError: unresolved variable @${expr.name} reached scalar evaluator.`); case "STRING_FUNC": return evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2); case "CASE_WHEN": return evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2); case "CONCAT_OP": { return evalStringFunc({ type: "STRING_FUNC", func: "CONCAT", args: [expr.left, expr.right] }, row, resolveFieldType, resolveFieldSemantics2); } case "SCALAR_ARITH": { const left = Number(evalScalarValueExpr(expr.left, row, resolveFieldType, resolveFieldSemantics2)); const right = Number(evalScalarValueExpr(expr.right, row, resolveFieldType, resolveFieldSemantics2)); switch (expr.op) { case "+": return left + right; case "-": return left - right; case "*": return left * right; case "/": return right !== 0 ? left / right : NaN; case "%": return right !== 0 ? left % right : NaN; } } } } function evalScalarValueExprNullable(expr, row, resolveFieldType, resolveFieldSemantics2) { switch (expr.type) { case "CASE_WHEN": return evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2); case "SCALAR_ARITH": { const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2); const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2); if (left === null || right === null) return null; const l = Number(left); const r = Number(right); switch (expr.op) { case "+": return l + r; case "-": return l - r; case "*": return l * r; case "/": return r !== 0 ? l / r : NaN; case "%": return r !== 0 ? l % r : NaN; } } case "CONCAT_OP": { const left = evalScalarValueExprNullable(expr.left, row, resolveFieldType, resolveFieldSemantics2); const right = evalScalarValueExprNullable(expr.right, row, resolveFieldType, resolveFieldSemantics2); return `${left ?? ""}${right ?? ""}`; } default: return evalScalarValueExpr(expr, row, resolveFieldType, resolveFieldSemantics2); } } function applyRoundOp(op, num, digits) { const factor = Math.pow(10, digits); const raw = Math[op](num * factor) / factor; if (digits > 0) return String(parseFloat(raw.toFixed(digits))); return String(raw); } function isHighSurrogate(codeUnit) { return codeUnit >= 55296 && codeUnit <= 56319; } function isLowSurrogate(codeUnit) { return codeUnit >= 56320 && codeUnit <= 57343; } function splitsSurrogatePair(value, index) { return index > 0 && index < value.length && isHighSurrogate(value.charCodeAt(index - 1)) && isLowSurrogate(value.charCodeAt(index)); } function normalizeSliceIndex(index, length) { if (Number.isNaN(index) || index === Number.NEGATIVE_INFINITY) return 0; if (index === Number.POSITIVE_INFINITY) return length; const integer2 = Math.trunc(index); return integer2 < 0 ? Math.max(length + integer2, 0) : Math.min(integer2, length); } function sliceSafePrefix(value, budget) { let end = Math.min(Math.max(0, budget), value.length); if (splitsSurrogatePair(value, end)) end -= 1; return value.slice(0, end); } function sliceSafeSuffix(value, budget) { let start = Math.max(0, value.length - budget); if (splitsSurrogatePair(value, start)) start += 1; return value.slice(start); } function sliceSafeRange(value, rawStart, rawEnd) { let start = normalizeSliceIndex(rawStart, value.length); let end = normalizeSliceIndex(rawEnd, value.length); if (end <= start) return ""; if (splitsSurrogatePair(value, start)) start += 1; if (splitsSurrogatePair(value, end)) end -= 1; return value.slice(start, Math.max(start, end)); } function makeSafePadding(pad, gap) { const repeated = pad.repeat(Math.ceil(gap / pad.length)); return sliceSafePrefix(repeated, gap); } var REGEXP_CACHE_MAX = 200; var regexpCache = /* @__PURE__ */ new Map(); function normalizeRegexpFlags(flags) { if (/[^ims]/.test(flags)) { throw new Error("ArgumentError: regular expression flags may contain only i, m, or s."); } if (new Set(flags).size !== flags.length) { throw new Error("ArgumentError: regular expression flags must not contain duplicates."); } return `${flags}u`; } function compileRegexp(pattern, flags, global = false) { const normalizedFlags = normalizeRegexpFlags(flags) + (global ? "g" : ""); const key = `${pattern}\0${normalizedFlags}`; const cached2 = regexpCache.get(key); if (cached2 !== void 0) { cached2.lastIndex = 0; return cached2; } let regexp; try { regexp = new RegExp(pattern, normalizedFlags); } catch (error51) { const detail = error51 instanceof Error ? error51.message : String(error51); throw new Error(`ArgumentError: invalid regular expression: ${detail}`); } if (regexpCache.size >= REGEXP_CACHE_MAX) { const oldest = regexpCache.keys().next().value; if (oldest !== void 0) regexpCache.delete(oldest); } regexpCache.set(key, regexp); return regexp; } function assertRegexpReplacement(replacement) { if (replacement.includes("$`") || replacement.includes("$'")) { throw new Error("ArgumentError: REGEXP_REPLACE replacement must not contain $` or $'."); } } function parseRegexpOccurrence(arg) { if (arg === void 0) return 0; if (!/^\d+$/.test(arg)) { throw new Error("ArgumentError: REGEXP_REPLACE occurrence must be a non-negative integer."); } return Number(arg); } function expandRegexpReplacement(replacement, match, captures, namedGroups) { let result = ""; for (let i = 0; i < replacement.length; i += 1) { const char = replacement[i]; if (char !== "$" || i + 1 >= replacement.length) { result += char; continue; } const next = replacement[i + 1]; if (next === "$") { result += "$"; i += 1; continue; } if (next === "&") { result += match; i += 1; continue; } if (next === "<" && namedGroups !== void 0) { const end = replacement.indexOf(">", i + 2); if (end >= 0) { result += namedGroups[replacement.slice(i + 2, end)] ?? ""; i = end; continue; } } if (/\d/.test(next)) { const secondDigit = replacement[i + 2]; if (secondDigit !== void 0 && /\d/.test(secondDigit)) { const twoDigitIndex = Number(next + secondDigit); if (twoDigitIndex >= 1 && twoDigitIndex <= captures.length) { result += captures[twoDigitIndex - 1] ?? ""; i += 2; continue; } } const oneDigitIndex = Number(next); if (oneDigitIndex >= 1 && oneDigitIndex <= captures.length) { result += captures[oneDigitIndex - 1] ?? ""; i += 1; continue; } } result += "$"; } return result; } function replaceNthMatch(input, globalRe, replacement, n) { let matchCount = 0; return input.replace(globalRe, (match, ...callbackArgs) => { matchCount += 1; if (matchCount !== n) return match; const lastArg = callbackArgs[callbackArgs.length - 1]; const hasNamedGroups = typeof lastArg === "object" && lastArg !== null; const capturesEnd = callbackArgs.length - (hasNamedGroups ? 3 : 2); const captures = callbackArgs.slice(0, capturesEnd); const namedGroups = hasNamedGroups ? lastArg : void 0; return expandRegexpReplacement(replacement, match, captures, namedGroups); }); } function evalStringFunc(expr, row, resolveFieldType, resolveFieldSemantics2) { const args = expr.args.map((a) => evalStringFuncArg(a, row, resolveFieldType, resolveFieldSemantics2)); switch (expr.func) { case "UPPER": return (args[0] ?? "").toUpperCase(); case "LOWER": return (args[0] ?? "").toLowerCase(); case "TRIM": return (args[0] ?? "").trim(); case "LTRIM": return (args[0] ?? "").trimStart(); case "RTRIM": return (args[0] ?? "").trimEnd(); case "LENGTH": return String((args[0] ?? "").length); case "LENGTH_CHAR": assertArity("LENGTH_CHAR", args, 1, 1); return String([...args[0] ?? ""].length); case "SUBSTRING": { const str = args[0] ?? ""; const start = Math.max(0, Number(args[1] ?? "1") - 1); const len = args[2] !== void 0 ? Number(args[2]) : void 0; return sliceSafeRange(str, start, len !== void 0 ? start + len : str.length); } case "LEFT": { assertArity("LEFT", args, 2, 2); const str = args[0]; const n = Math.trunc(Number(args[1])); return Number.isNaN(n) || n <= 0 ? "" : sliceSafePrefix(str, n); } case "RIGHT": { assertArity("RIGHT", args, 2, 2); const str = args[0]; const n = Math.trunc(Number(args[1])); return Number.isNaN(n) || n <= 0 ? "" : sliceSafeSuffix(str, n); } case "INSTR": assertArity("INSTR", args, 2, 2); return String(args[0].indexOf(args[1]) + 1); case "LPAD": case "RPAD": { assertArity(expr.func, args, 2, 3); const str = args[0]; const n = Math.trunc(Number(args[1])); if (Number.isNaN(n) || n <= 0) return ""; if (str.length >= n) return sliceSafePrefix(str, n); const pad = args[2] ?? " "; if (pad === "") return str; const padding = makeSafePadding(pad, n - str.length); return expr.func === "LPAD" ? padding + str : str + padding; } case "GREATEST": case "LEAST": assertArity(expr.func, args, 2); return selectScalarExtreme(args, expr.func === "GREATEST" ? "greatest" : "least"); case "CONCAT": return args.join(""); case "REPLACE": { const str = args[0] ?? ""; const from = args[1] ?? ""; const to = args[2] ?? ""; return from === "" ? str : str.split(from).join(to); } case "REGEXP_LIKE": { assertArity("REGEXP_LIKE", args, 2, 3); return compileRegexp(args[1], args[2] ?? "").test(args[0]) ? "1" : "0"; } case "REGEXP_REPLACE": { assertArity("REGEXP_REPLACE", args, 3, 5); assertRegexpReplacement(args[2]); const occurrence = parseRegexpOccurrence(args[4]); const regexp = compileRegexp(args[1], args[3] ?? "", true); return occurrence === 0 ? args[0].replace(regexp, args[2]) : replaceNthMatch(args[0], regexp, args[2], occurrence); } case "REGEXP_SUBSTR": { assertArity("REGEXP_SUBSTR", args, 2, 3); return compileRegexp(args[1], args[2] ?? "").exec(args[0])?.[0] ?? ""; } case "TRANSLATE": { assertArity("TRANSLATE", args, 3, 3); const from = [...args[1]]; const to = [...args[2]]; if (from.length !== to.length) { throw new Error( `ArgumentError: TRANSLATE \u306E from \u3068 to \u306F\u540C\u3058\u6587\u5B57\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF08from=${from.length}, to=${to.length}\uFF09` ); } const map2 = /* @__PURE__ */ new Map(); from.forEach((ch, i) => { if (!map2.has(ch)) map2.set(ch, to[i]); }); return [...args[0]].map((ch) => map2.get(ch) ?? ch).join(""); } case "COALESCE": return args.find((a) => a !== "") ?? ""; case "NULLIF": return (args[0] ?? "") === (args[1] ?? "") ? "" : args[0] ?? ""; case "ISNULL": return (args[0] ?? "") !== "" ? args[0] ?? "" : args[1] ?? ""; case "ROUND": return applyRoundOp("round", Number(args[0] ?? "0"), Number(args[1] ?? "0")); case "FLOOR": return applyRoundOp("floor", Number(args[0] ?? "0"), Number(args[1] ?? "0")); case "CEIL": return applyRoundOp("ceil", Number(args[0] ?? "0"), Number(args[1] ?? "0")); case "TRUNCATE": assertArity("TRUNCATE", args, 1, 2); return applyRoundOp("trunc", Number(args[0]), Number(args[1] ?? "0")); case "CAST": { const val = args[0] ?? ""; const castType = args[1] ?? "TEXT"; if (castType === "NUMBER") { const n = Number(val); return isNaN(n) ? val : String(n); } return val; } case "FORMAT": { const num = Number(args[0] ?? "0"); const pattern = args[1] ?? "0"; return applyFormat(num, pattern); } case "YEAR": { const d = args[0] ?? ""; return d.length >= 4 ? String(parseInt(d.slice(0, 4), 10)) : ""; } case "MONTH": { const d = args[0] ?? ""; return d.length >= 7 ? String(parseInt(d.slice(5, 7), 10)) : ""; } case "DAY": { const d = args[0] ?? ""; return d.length >= 10 ? String(parseInt(d.slice(8, 10), 10)) : ""; } case "DAYOFWEEK": assertArity(expr.func, args, 1, 1); return isValidYmd(args[0]) ? String(dayOfWeekIndex(args[0]) + 1) : ""; case "QUARTER": assertArity(expr.func, args, 1, 1); return isValidYmd(args[0]) ? String(Math.ceil(Number(args[0].slice(5, 7)) / 3)) : ""; case "WEEK": assertArity(expr.func, args, 1, 1); return isValidYmd(args[0]) ? String(isoWeekNumber(args[0])) : ""; case "DATE_FORMAT": return applyDateFormat(args[0] ?? "", args[1] ?? ""); case "DATEDIFF": return applyDateDiff(args[0] ?? "", args[1] ?? ""); case "DATE_ADD": return applyDateAdd(args[0] ?? "", Number(args[1] ?? "0"), (args[2] ?? "DAY").toUpperCase()); case "LAST_DAY": assertArity("LAST_DAY", args, 1, 1); return applyLastDay(args[0]); case "ABS": return String(Math.abs(Number(args[0] ?? "0"))); case "MOD": { const a = Number(args[0] ?? "0"); const b = Number(args[1] ?? "0"); return String(b !== 0 ? a % b : NaN); } case "POWER": return String(Math.pow(Number(args[0] ?? "0"), Number(args[1] ?? "0"))); case "SQRT": return String(Math.sqrt(Number(args[0] ?? "0"))); case "CURRENT_DATE": { const now = /* @__PURE__ */ new Date(); const y = now.getFullYear(); const m = String(now.getMonth() + 1).padStart(2, "0"); const d = String(now.getDate()).padStart(2, "0"); return `${y}-${m}-${d}`; } case "CURRENT_TIMESTAMP": return (/* @__PURE__ */ new Date()).toISOString(); } } function assertArity(func, args, min, max = Number.POSITIVE_INFINITY) { if (args.length >= min && args.length <= max) return; const expected = min === max ? String(min) : max === Number.POSITIVE_INFINITY ? `${min} or more` : `${min} to ${max}`; throw new Error(`ArgumentError: ${func} expects ${expected} argument(s).`); } function parseDateParts(s) { return { y: s.slice(0, 4) || "0000", mo: s.slice(5, 7) || "01", d: s.slice(8, 10) || "01", h: s.length >= 13 ? s.slice(11, 13) : "00", mi: s.length >= 16 ? s.slice(14, 16) : "00", sec: s.length >= 19 ? s.slice(17, 19) : "00" }; } function ymdUtcDate(dateStr) { const date5 = /* @__PURE__ */ new Date(0); date5.setUTCHours(0, 0, 0, 0); date5.setUTCFullYear( Number(dateStr.slice(0, 4)), Number(dateStr.slice(5, 7)) - 1, Number(dateStr.slice(8, 10)) ); return date5; } function isValidYmd(dateStr) { const ymd = dateStr.slice(0, 10); if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) return false; const date5 = ymdUtcDate(ymd); return date5.getUTCFullYear() === Number(ymd.slice(0, 4)) && date5.getUTCMonth() + 1 === Number(ymd.slice(5, 7)) && date5.getUTCDate() === Number(ymd.slice(8, 10)); } function dayOfWeekIndex(dateStr) { return ymdUtcDate(dateStr).getUTCDay(); } function isoWeekThursday(dateStr) { const date5 = ymdUtcDate(dateStr); const isoDay = date5.getUTCDay() || 7; date5.setUTCDate(date5.getUTCDate() + 4 - isoDay); return date5; } function isoWeekYear(dateStr) { return isoWeekThursday(dateStr).getUTCFullYear(); } function isoWeekNumber(dateStr) { const thursday = isoWeekThursday(dateStr); const year = thursday.getUTCFullYear(); const jan4 = ymdUtcDate(`${String(year).padStart(4, "0")}-01-04`); const jan4IsoDay = jan4.getUTCDay() || 7; jan4.setUTCDate(jan4.getUTCDate() + 4 - jan4IsoDay); return 1 + Math.round((thursday.getTime() - jan4.getTime()) / (7 * 864e5)); } function applyDateFormat(dateStr, pattern) { if (!dateStr || dateStr.length < 10) return ""; const { y, mo, d, h, mi, sec } = parseDateParts(dateStr); const validYmd = isValidYmd(dateStr); return pattern.replace(/%[YymcdeHiswavG]/g, (specifier) => { switch (specifier) { case "%Y": return y; case "%y": return y.slice(2); case "%m": return mo; case "%c": return String(parseInt(mo, 10)); case "%d": return d; case "%e": return String(parseInt(d, 10)); case "%H": return h; case "%i": return mi; case "%s": return sec; case "%w": return validYmd ? String(dayOfWeekIndex(dateStr)) : ""; case "%a": return validYmd ? ["\u65E5", "\u6708", "\u706B", "\u6C34", "\u6728", "\u91D1", "\u571F"][dayOfWeekIndex(dateStr)] : ""; case "%v": return validYmd ? String(isoWeekNumber(dateStr)).padStart(2, "0") : ""; case "%G": return validYmd ? String(isoWeekYear(dateStr)).padStart(4, "0") : ""; default: return specifier; } }); } function applyDateDiff(date1, date22) { if (date1.length < 10 || date22.length < 10) return "0"; const p1 = parseDateParts(date1); const p2 = parseDateParts(date22); const d1 = Date.UTC(+p1.y, +p1.mo - 1, +p1.d); const d2 = Date.UTC(+p2.y, +p2.mo - 1, +p2.d); return String(Math.round((d1 - d2) / 864e5)); } function applyDateAdd(dateStr, n, unit) { if (unit !== "YEAR" && unit !== "MONTH" && unit !== "DAY") { throw new Error("ArgumentError: DATE_ADD unit must be YEAR, MONTH, or DAY."); } if (!dateStr || dateStr.length < 10) return dateStr; const { y, mo, d } = parseDateParts(dateStr); const dt = new Date(Date.UTC(+y, +mo - 1, +d)); switch (unit) { case "YEAR": dt.setUTCFullYear(dt.getUTCFullYear() + n); break; case "MONTH": dt.setUTCMonth(dt.getUTCMonth() + n); break; case "DAY": dt.setUTCDate(dt.getUTCDate() + n); break; } const ry = String(dt.getUTCFullYear()).padStart(4, "0"); const rmo = String(dt.getUTCMonth() + 1).padStart(2, "0"); const rd = String(dt.getUTCDate()).padStart(2, "0"); return `${ry}-${rmo}-${rd}`; } function applyLastDay(dateStr) { if (!dateStr || dateStr.length < 10) return dateStr; const { y, mo } = parseDateParts(dateStr); const dt = new Date(Date.UTC(+y, +mo, 0)); const ry = String(dt.getUTCFullYear()).padStart(4, "0"); const rmo = String(dt.getUTCMonth() + 1).padStart(2, "0"); const rd = String(dt.getUTCDate()).padStart(2, "0"); return `${ry}-${rmo}-${rd}`; } function applyFormat(num, pattern) { if (/^-?\d+$/.test(pattern.trim())) { return formatWithComma(num, Math.max(0, Number(pattern))); } const isPercent = pattern.endsWith("%"); const useComma = pattern.includes(","); const n = isPercent ? num * 100 : num; const dotIdx = pattern.replace(/%$/, "").lastIndexOf("."); const afterDot = dotIdx >= 0 ? pattern.slice(dotIdx + 1).replace(/%$/, "") : ""; const required0 = (afterDot.match(/0/g) ?? []).length; const optional2 = (afterDot.match(/#/g) ?? []).length; const maxDec = required0 + optional2; const formatted = n.toFixed(maxDec); let [intStr, decStr = ""] = formatted.split("."); if (optional2 > 0) { decStr = decStr.replace(/0+$/, ""); } const intFmt = useComma ? intStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : intStr; const result = decStr ? `${intFmt}.${decStr}` : intFmt; return isPercent ? result + "%" : result; } function formatWithComma(num, digits) { const formatted = num.toFixed(digits); const [intStr, decStr] = formatted.split("."); const intFmt = intStr.replace(/\B(?=(\d{3})+(?!\d))/g, ","); return decStr ? `${intFmt}.${decStr}` : intFmt; } function evalStringFuncArg(arg, row, resolveFieldType, resolveFieldSemantics2) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") return ""; if (arg.type === "NUMBER") return numberLiteralText(arg); return String(evalScalarValueExpr(arg, row, resolveFieldType, resolveFieldSemantics2)); } function resolveFieldRef(row, field) { const direct = row[field]; if (direct !== void 0) return direct; const dot = field.indexOf("."); if (dot > 0) { const fallback = row[field.slice(dot + 1)]; if (fallback !== void 0) return fallback; } return ""; } // src/engine/evalWhere.ts function evalWhere(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) { switch (expr.type) { case "BOOLEAN": return expr.value; case "BINARY": return evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2); case "NULL_CHECK": return evalNullCheck(expr, row); case "LOGICAL": return evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2); case "NOT": return !evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2); case "GROUP": return evalWhere(expr.expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2); case "EXISTS": { const exists = expr.resolved; return expr.not ? !exists : exists; } } } function evalBinary(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) { if (expr.op === "KLIKE" || expr.op === "NOT_KLIKE") { if (appliedKlikes?.has(expr)) return true; throw new Error("KLIKE / NOT KLIKE \u306F\u62BC\u3057\u4E0B\u3052\u6E08\u307F\u96C6\u5408\u306B\u542B\u307E\u308C\u306A\u3044\u305F\u3081 JavaScript \u5074\u3067\u306F\u8A55\u4FA1\u3067\u304D\u307E\u305B\u3093"); } const left = resolveField(expr.left, row, resolveFieldType, resolveFieldSemantics2); const fieldType = expr.left.type === "FIELD" ? resolveFieldType?.(expr.left) : void 0; const semantics = semanticsForLeft(expr.left, fieldType, resolveFieldSemantics2); return evalOp(expr.op, left, expr.right, row, fieldType, resolveFieldType, semantics, resolveFieldSemantics2); } function evalOp(op, leftStr, right, row, fieldType, resolveFieldType, semantics = syntheticSemantics("string"), resolveFieldSemantics2) { if (op === "IN" || op === "NOT_IN") { let values = null; if (right.type === "IN_LIST") { assertResolvedInListValues2(right.values); values = new Set(right.values.map((v) => v.type === "NUMBER" ? fieldType === "NUMBER" ? numberLiteralText(v) : String(v.value) : v.value)); } if (right.type === "SUBQUERY_IN_LIST") { values = right.resolved; } if (values === null) return op === "NOT_IN"; const contains = typedInContains(leftStr, values, fieldType); return op === "IN" ? contains : !contains; } if (op === "LIKE") { const pattern = resolveValue(right, row, resolveFieldType); return matchLike(leftStr, pattern); } if (op === "NOT_LIKE") { const pattern = resolveValue(right, row, resolveFieldType); return !matchLike(leftStr, pattern); } if (op === "KLIKE" || op === "NOT_KLIKE") { throw new Error("KLIKE / NOT KLIKE \u306F JavaScript \u5074\u3067\u306F\u8A55\u4FA1\u3067\u304D\u307E\u305B\u3093\uFF08SIMPLE SELECT \u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\uFF09"); } const rightStr = resolveValue(right, row, resolveFieldType, resolveFieldSemantics2); return compareScalarValues(op, leftStr, rightStr, semantics); } var NUMERIC_STRING_FUNCTIONS = /* @__PURE__ */ new Set([ "LENGTH", "LENGTH_CHAR", "INSTR", "ROUND", "FLOOR", "CEIL", "TRUNCATE", "YEAR", "MONTH", "DAY", "DATEDIFF", "ABS", "MOD", "POWER", "SQRT", "DAYOFWEEK", "QUARTER", "WEEK" ]); function semanticsForLeft(left, fieldType, resolveSemantics) { if (left.type === "FIELD") { return resolveSemantics?.(left) ?? (fieldType ? resolveFieldSemantics({ fieldType }) : syntheticSemantics("string")); } if (left.type === "ARITH_FIELD") return syntheticSemantics("number"); if (left.type === "FUNC_FIELD") { return syntheticSemantics(NUMERIC_STRING_FUNCTIONS.has(left.expr.func) ? "number" : "string"); } if (left.type === "CASE_FIELD") { const results = [ ...left.expr.branches.map((branch) => branch.result), ...left.expr.elseResult ? [left.expr.elseResult] : [] ]; const modes = results.map((result) => { if (result.type === "NUMBER" || result.type === "ARITH") return syntheticSemantics("number"); if (result.type === "STRING_FUNC") { return syntheticSemantics(NUMERIC_STRING_FUNCTIONS.has(result.func) ? "number" : "string"); } if (result.type === "FIELD_REF") { const dot = result.field.indexOf("."); const ref = dot > 0 ? { type: "FIELD", tableAlias: result.field.slice(0, dot), field: result.field.slice(dot + 1) } : { type: "FIELD", tableAlias: null, field: result.field }; return resolveSemantics?.(ref) ?? syntheticSemantics("string"); } return syntheticSemantics("string"); }); if (modes.length > 0 && modes.every((mode) => mode.compareMode === modes[0].compareMode)) return modes[0]; } return syntheticSemantics("string"); } var STRING_ARRAY_FIELD_TYPES = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]); var OBJECT_ARRAY_FIELD_TYPES = /* @__PURE__ */ new Set([ "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT", "STATUS_ASSIGNEE" ]); var SINGLE_OBJECT_FIELD_TYPES = /* @__PURE__ */ new Set(["CREATOR", "MODIFIER"]); function typedInContains(leftStr, values, fieldType) { const fallback = () => values.has(leftStr); if (fieldType === void 0) return fallback(); if (fieldType === "NUMBER") { const semantics = syntheticSemantics("number"); return [...values].some((value) => compareScalarValues("=", leftStr, value, semantics)); } let parsed; if (STRING_ARRAY_FIELD_TYPES.has(fieldType) || OBJECT_ARRAY_FIELD_TYPES.has(fieldType) || SINGLE_OBJECT_FIELD_TYPES.has(fieldType)) { try { parsed = JSON.parse(leftStr); } catch { return fallback(); } } else { return fallback(); } if (STRING_ARRAY_FIELD_TYPES.has(fieldType)) { if (!Array.isArray(parsed) || !parsed.every((item) => typeof item === "string")) { return fallback(); } if (parsed.length === 0 && values.has("")) return true; return parsed.some((item) => values.has(item)); } if (OBJECT_ARRAY_FIELD_TYPES.has(fieldType)) { if (!Array.isArray(parsed) || !parsed.every(hasStringCode)) return fallback(); if (parsed.length === 0 && values.has("")) return true; return parsed.some((item) => values.has(item.code)); } if (!hasStringCode(parsed)) return fallback(); return values.has(parsed.code); } function hasStringCode(value) { return value !== null && typeof value === "object" && !Array.isArray(value) && typeof value.code === "string"; } function assertResolvedInListValues2(values) { const unresolved = values.find((item) => item.type === "VARIABLE"); if (unresolved?.type === "VARIABLE") { throw new Error(`ParseError: unresolved batch variable @${unresolved.name}.`); } } function evalNullCheck(expr, row) { const val = resolveField(expr.field, row); return expr.not ? val !== "" : val === ""; } function evalLogical(expr, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) { if (expr.op === "AND") { return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) && evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2); } return evalWhere(expr.left, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2) || evalWhere(expr.right, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2); } function resolveField(field, row, resolveFieldType, resolveFieldSemantics2) { if (field.type === "FUNC_FIELD") return evalStringFunc(field.expr, row); if (field.type === "ARITH_FIELD") return String(evalArithExpr(field.expr, row)); if (field.type === "CASE_FIELD") return evalCaseWhen(field.expr, row, resolveFieldType, resolveFieldSemantics2); const key = field.tableAlias ? `${field.tableAlias}.${field.field}` : field.field; return resolveFieldRef(row, key); } function resolveValue(value, row, resolveFieldType, resolveFieldSemantics2) { switch (value.type) { case "VARIABLE": throw new Error(`ParseError: unresolved batch variable @${value.name}.`); case "VARIABLE_IN_LIST": throw new Error(`ParseError: unresolved batch array variable @${value.name}.`); case "STRING": return value.value; case "NUMBER": return numberLiteralText(value); case "KINTONE_FUNC": return resolveKintoneFunc(value.name); case "IN_LIST": return ""; // IN は evalOp で別処理 case "SUBQUERY_IN_LIST": return ""; // IN (SELECT) は evalOp で別処理 case "SCALAR_SUBQUERY": return value.resolved; case "ARITH_VALUE": if (value.expr.type === "FIELD_REF") return resolveFieldRef(row, value.expr.field); if (value.expr.type === "STRING_FUNC") return evalStringFunc(value.expr, row); return String(evalArithExpr(value.expr, row)); case "CASE_VALUE": return evalCaseWhen(value.expr, row, resolveFieldType, resolveFieldSemantics2); case "ARRAY": return value.elements.map((e) => e.value).join(","); } } function evalCaseWhen(expr, row, resolveFieldType, resolveFieldSemantics2) { for (const branch of expr.branches) { if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) { return evalCaseResult(branch.result, row, resolveFieldType, resolveFieldSemantics2); } } if (expr.elseResult !== null) { return evalCaseResult(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2); } return ""; } function evalCaseWhenNullable(expr, row, resolveFieldType, resolveFieldSemantics2) { for (const branch of expr.branches) { if (evalWhere(branch.condition, row, resolveFieldType, void 0, resolveFieldSemantics2)) { return evalCaseResultNullable(branch.result, row, resolveFieldType, resolveFieldSemantics2); } } return expr.elseResult === null ? null : evalCaseResultNullable(expr.elseResult, row, resolveFieldType, resolveFieldSemantics2); } function evalCaseResultNullable(result, row, resolveFieldType, resolveFieldSemantics2) { if (result.type === "ARRAY") return result.elements.map((entry) => entry.value).join(","); if (result.type === "FIELD_REF") return row[result.field] ?? ""; if (result.type === "ARITH") return evalArithExpr(result, row); return evalScalarValueExprNullable(result, row, resolveFieldType, resolveFieldSemantics2); } function evalCaseResult(result, row, resolveFieldType, resolveFieldSemantics2) { if (result.type === "ARRAY") return result.elements.map((e) => e.value).join(","); if (result.type === "FIELD_REF") { return row[result.field] ?? ""; } if (result.type === "ARITH") { return String(evalArithExpr(result, row)); } return String(evalScalarValueExpr(result, row, resolveFieldType, resolveFieldSemantics2)); } function resolveKintoneFunc(name) { const now = /* @__PURE__ */ new Date(); switch (name) { case "TODAY": { const y = now.getFullYear(); const m = String(now.getMonth() + 1).padStart(2, "0"); const d = String(now.getDate()).padStart(2, "0"); return `${y}-${m}-${d}`; } case "NOW": return now.toISOString(); case "LOGINUSER": return ""; } } var likeRegexCache = /* @__PURE__ */ new Map(); var LIKE_REGEX_CACHE_MAX = 200; function matchLike(value, pattern) { if (!likePatternHasWildcard(pattern)) { return value.includes(pattern); } let regex = likeRegexCache.get(pattern); if (!regex) { let regexStr = "^"; for (let i = 0; i < pattern.length; i++) { const ch = pattern[i]; if (ch === "%") { regexStr += ".*"; } else if (ch === "_") { regexStr += "."; } else { regexStr += ch.replace(/[.+*?^${}()|[\]\\]/g, "\\$&"); } } regexStr += "$"; regex = new RegExp(regexStr, "u"); if (likeRegexCache.size >= LIKE_REGEX_CACHE_MAX) likeRegexCache.clear(); likeRegexCache.set(pattern, regex); } return regex.test(value); } // src/core/dmlCustomCheck.ts function collectCheckFieldRefs(groups) { return collectRefs2(groups); } function collectCheckComparisonFieldRefs(groups) { return collectRefs2(groups.flatMap((group) => group.rules.map((rule) => rule.condition))); } function collectRefs2(root) { const refs = []; const seen = /* @__PURE__ */ new Set(); const visit = (node) => { if (Array.isArray(node)) { node.forEach(visit); return; } if (node === null || typeof node !== "object") return; const obj = node; if (obj.type === "EXISTS" || obj.type === "SUBQUERY_IN_LIST" || obj.type === "SCALAR_SUBQUERY") { throw customCheckParseError("CHECK \u306B\u30B5\u30D6\u30AF\u30A8\u30EA\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"); } if (obj.type === "FIELD" && typeof obj.field === "string") { add(typeof obj.tableAlias === "string" ? obj.tableAlias : null, obj.field); } else if (obj.type === "FIELD_REF" && typeof obj.field === "string") { const dot = obj.field.indexOf("."); add(dot > 0 ? obj.field.slice(0, dot) : null, dot > 0 ? obj.field.slice(dot + 1) : obj.field); } for (const value of Object.values(obj)) visit(value); }; const add = (tableAlias, field) => { if (/^(COUNT|SUM|AVG|MIN|MAX|GROUP_CONCAT|STDDEV_POP|STDDEV_SAMP|VAR_POP|VAR_SAMP|MEDIAN|MODE)\(/i.test(field)) { throw customCheckParseError("CHECK \u306B\u96C6\u7D04\u95A2\u6570\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"); } const key = `${tableAlias ?? ""}\0${field}`; if (!seen.has(key)) { seen.add(key); refs.push({ tableAlias, field }); } }; visit(root); return refs; } function customCheckParseError(message) { return new ParseError(message, { kind: "EOF" /* EOF */, value: "CHECK", pos: 0 }); } function evaluateCustomChecks(groups, row, resolveFieldType) { const errors = []; groups.forEach((group, groupIndex) => { for (const rule of group.rules) { if (!evalWhere(rule.condition, row, resolveFieldType)) continue; const value = evalScalarValueExpr(rule.message, row); errors.push({ groupIndex, message: value == null ? "" : String(value) }); break; } }); return errors; } // src/converter/dmlToKintone.ts function assertDmlWhereIsSafe(where) { if (!whereHasLike(where)) return; throw new DmlConvertError( "UPDATE / DELETE \u306E WHERE \u306B LIKE / NOT LIKE \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002LIKE \u306F kSQL \u306E\u610F\u5473\u8AD6\u306B\u5F93\u3063\u3066 JS \u3067\u8A55\u4FA1\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u304C\u3001\u89AA\u30EC\u30B3\u30FC\u30C9 DML \u306B\u306F JS \u8A55\u4FA1\u7D4C\u8DEF\u304C\u306A\u3044\u305F\u3081\u3001\u5B89\u5168\u4E0A\u62D2\u5426\u3057\u307E\u3057\u305F\u3002SELECT \u3067\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u756A\u53F7\u3092\u78BA\u8A8D\u3057\u3001IN \u307E\u305F\u306F\u5B8C\u5168\u4E00\u81F4\u3067\u5BFE\u8C61\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002" ); } var USER_TYPES = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]); var ARRAY_TYPES = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]); function insertToPostBatches(stmt, fieldTypes = /* @__PURE__ */ new Map()) { const allRecords = stmt.values.map( (row) => buildInsertRecord(stmt.fields, row, fieldTypes) ); return chunk(allRecords, 100).map((records) => ({ app: stmt.appId, records })); } function buildInsertRecord(fields, row, fieldTypes) { const record2 = {}; fields.forEach((field, i) => { const val = row[i]; if (val.type === "CASE_VALUE") { record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) }; } else { record2[field] = { value: toKintoneValue(val, fieldTypes.get(field)) }; } }); return record2; } function updateToGetQuery(stmt) { assertDmlWhereIsSafe(stmt.where); const checkFields = collectUpdateCheckTargetFields(stmt); return { app: stmt.appId, query: whereToKintone(stmt.where), fields: ["$id", ...checkFields], totalCount: false }; } function updateToPutBatches(stmt, ids, fieldTypes = /* @__PURE__ */ new Map()) { const record2 = buildUpdateRecord(stmt.assignments, fieldTypes); return chunk(ids, 100).map((batch) => ({ app: stmt.appId, records: batch.map((id) => ({ id, record: record2 })) })); } function buildUpdateRecord(assignments, fieldTypes) { const record2 = {}; for (const { field, value } of assignments) { if (value.type === "ARITH" || value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP" || value.type === "CASE_VALUE" || value.type === "STRING_FUNC" || value.type === "SOURCE_FIELD") continue; record2[field] = { value: toKintoneValue(value, fieldTypes.get(field)) }; } return record2; } function hasArithAssignment(stmt) { return stmt.assignments.some( (a) => a.value.type === "ARITH" || a.value.type === "SCALAR_ARITH" || a.value.type === "CONCAT_OP" || a.value.type === "CASE_VALUE" ); } function hasRowDependentAssignment(stmt) { return stmt.assignments.some( (a) => a.value.type === "ARITH" || a.value.type === "SCALAR_ARITH" || a.value.type === "CONCAT_OP" || a.value.type === "CASE_VALUE" || a.value.type === "STRING_FUNC" ); } function updateToGetQueryForArith(stmt) { assertDmlWhereIsSafe(stmt.where); const refFields = /* @__PURE__ */ new Set(); for (const { value } of stmt.assignments) { if (value.type === "ARITH") { collectArithFields2(value, refFields); } else if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") { collectScalarValueFields2(value, refFields); } else if (value.type === "STRING_FUNC") { collectStringFuncFields2(value, refFields); } else if (value.type === "CASE_VALUE") { collectCaseFields(value.expr, refFields); } } collectUpdateCheckTargetFields(stmt).forEach((field) => refFields.add(field)); return { app: stmt.appId, query: whereToKintone(stmt.where), fields: ["$id", ...refFields], totalCount: false }; } function collectArithFields2(expr, out) { collectArithNode2(expr.left, out); collectArithNode2(expr.right, out); } function collectArithNode2(node, out) { if (node.type === "FIELD_REF") out.add(node.field); else if (node.type === "ARITH") collectArithFields2(node, out); else if (node.type === "STRING_FUNC") collectStringFuncFields2(node, out); } function collectStringFuncFields2(expr, out) { for (const arg of expr.args) collectStringFuncArgFields2(arg, out); } function collectStringFuncArgFields2(arg, out) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") { collectAggOperandFields2(arg, out); return; } collectScalarValueFields2(arg, out); } function collectScalarValueFields2(expr, out) { if (expr.type === "FIELD") { out.add(expr.tableAlias ? `${expr.tableAlias}.${expr.field}` : expr.field); return; } if (expr.type === "STRING_FUNC") { collectStringFuncFields2(expr, out); return; } if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { collectScalarValueFields2(expr.left, out); collectScalarValueFields2(expr.right, out); return; } if (expr.type === "CASE_WHEN") collectCaseFields(expr, out); } function collectAggOperandFields2(node, out) { if (node.type === "AGG_REF") { if (node.arg.type !== "WILDCARD") collectAggregateArgFields2(node.arg, out); return; } if (node.type === "AGG_ARITH") { collectAggOperandFields2(node.left, out); collectAggOperandFields2(node.right, out); } } function collectAggregateArgFields2(node, out) { if (node.type === "FIELD_REF" || node.type === "ARITH") collectArithNode2(node, out); else collectScalarValueFields2(node, out); } function collectCaseResultFields(result, out) { if (result.type === "ARRAY") return; if (result.type === "FIELD_REF" || result.type === "ARITH") { collectArithNode2(result, out); return; } collectScalarValueFields2(result, out); } function collectCaseFields(expr, out) { for (const branch of expr.branches) { collectConditionFields(branch.condition, out); collectCaseResultFields(branch.result, out); } if (expr.elseResult !== null) { collectCaseResultFields(expr.elseResult, out); } } function collectConditionFields(expr, out) { switch (expr.type) { case "BINARY": if (expr.left.type === "FIELD") out.add(expr.left.field); else if (expr.left.type === "ARITH_FIELD") collectArithNode2(expr.left.expr, out); break; case "NULL_CHECK": if (expr.field.type === "FIELD") out.add(expr.field.field); break; case "LOGICAL": collectConditionFields(expr.left, out); collectConditionFields(expr.right, out); break; case "NOT": case "GROUP": collectConditionFields(expr.expr, out); break; case "EXISTS": case "BOOLEAN": break; } } function updateToPutBatchesArith(stmt, records, fieldTypes = /* @__PURE__ */ new Map()) { const updateRecords = records.map((raw) => { const id = Number(raw["$id"].value); const row = kintoneRecordToProcessRow(raw); const record2 = {}; for (const { field, value } of stmt.assignments) { record2[field] = { value: evaluateUpdateAssignmentValue(value, row, fieldTypes.get(field), raw) }; } return { id, record: record2 }; }); return chunk(updateRecords, 100).map((batch) => ({ app: stmt.appId, records: batch })); } function evaluateUpdateAssignmentValue(value, row, fieldType, raw) { if (value.type === "ARITH") { return String(raw ? evalArith(value, raw) : evalArithExpr(value, row)); } if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") { return String(evalScalarValueExpr(value, row)); } if (value.type === "STRING_FUNC") return evalStringFunc(value, row); if (value.type === "CASE_VALUE") return evalCaseWhenValue(value.expr, row, fieldType); if (value.type === "SOURCE_FIELD") { throw new DmlConvertError("SOURCE_FIELD \u306F UPDATE ... FROM \u5C02\u7528\u3067\u3059"); } return toKintoneValue(value, fieldType); } function evaluateSubtableAssignmentValue(value, row, resolveFieldType) { if (value.type === "STRING") return value.value; if (value.type === "NUMBER") return numberLiteralText(value); if (value.type === "ARITH") return String(evalArithExpr(value, row)); if (value.type === "CASE_VALUE") return evalCaseWhen(value.expr, row, resolveFieldType); throw new Error(`${value.type} \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306E\u5024\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093`); } var UPDATE_FROM_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set([ "CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT", "FILE" ]); function updateFromToPutBatches(stmt, matched, fieldTypes = /* @__PURE__ */ new Map()) { const updateRecords = matched.map(({ target, source }) => { const id = Number(target["$id"]?.value); if (!Number.isSafeInteger(id) || id <= 0) { throw new DmlConvertError("UPDATE ... FROM \u306E\u5BFE\u8C61\u30EC\u30B3\u30FC\u30C9\u756A\u53F7\u304C\u4E0D\u6B63\u3067\u3059"); } const targetRow = kintoneRecordToProcessRow(target); const record2 = {}; for (const { field, value } of stmt.assignments) { const fieldType = fieldTypes.get(field); if (value.type === "SOURCE_FIELD") { if (UPDATE_FROM_UNSUPPORTED_TYPES.has(fieldType ?? "")) { throw new DmlConvertError(`UPDATE ... FROM \u306E SOURCE_FIELD \u306F ${fieldType} \u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9: ${field}\uFF09`); } if (!Object.prototype.hasOwnProperty.call(source, value.field)) { throw new DmlConvertError(`UPDATE ... FROM \u306E\u30BD\u30FC\u30B9\u5217 ${value.field} \u304C\u5B58\u5728\u3057\u307E\u305B\u3093`); } const raw = source[value.field]; if (typeof raw !== "string") { throw new DmlConvertError(`UPDATE ... FROM \u306E SOURCE_FIELD \u306F\u30B9\u30AB\u30E9\u30FC\u5024\u306E\u307F\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u3059\uFF08\u5217: ${value.field}\uFF09`); } if ((fieldType === "NUMBER" || fieldType === "CALC") && raw !== "" && !Number.isFinite(Number(raw))) { throw new DmlConvertError(`\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9 ${field} \u306B\u5909\u63DB\u3067\u304D\u306A\u3044\u5024\u3067\u3059: ${raw}`); } record2[field] = { value: toKintoneValue({ type: "STRING", value: raw }, fieldType) }; } else if (value.type === "STRING_FUNC") { throw new DmlConvertError("UPDATE ... FROM \u306E SET \u3067\u306F\u6587\u5B57\u5217\u95A2\u6570\u3092\u76F4\u63A5\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"); } else if (value.type === "ARITH") { record2[field] = { value: String(evalArith(value, target)) }; } else if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") { record2[field] = { value: String(evalScalarValueExpr(value, targetRow)) }; } else if (value.type === "CASE_VALUE") { record2[field] = { value: evalCaseWhenValue(value.expr, targetRow, fieldType) }; } else { record2[field] = { value: toKintoneValue(value, fieldType) }; } } return { id, record: record2 }; }); return chunk(updateRecords, 100).map((records) => ({ app: stmt.appId, records })); } function kintoneRecordToProcessRow(raw) { return Object.fromEntries( Object.entries(raw).map(([k, v]) => [ k, typeof v.value === "string" ? v.value : JSON.stringify(v.value ?? "") ]) ); } function evalArith(expr, raw) { const l = resolveArithOperand(expr.left, raw); const r = resolveArithOperand(expr.right, raw); switch (expr.op) { case "+": return l + r; case "-": return l - r; case "*": return l * r; case "/": if (r === 0) throw new DmlConvertError("\u7B97\u8853\u5F0F\u3067\u30BC\u30ED\u9664\u7B97\u304C\u767A\u751F\u3057\u307E\u3057\u305F"); return l / r; case "%": if (r === 0) throw new DmlConvertError("\u7B97\u8853\u5F0F\u3067\u30BC\u30ED\u9664\u7B97\u304C\u767A\u751F\u3057\u307E\u3057\u305F"); return l % r; } } function resolveArithOperand(operand, raw) { if (operand.type === "NUMBER") return operand.value; if (operand.type === "ARITH") return evalArith(operand, raw); if (operand.type === "STRING_FUNC") throw new DmlConvertError( "UPDATE SET \u306E\u7B97\u8853\u5F0F\u3067\u306F\u6587\u5B57\u5217\u95A2\u6570\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093" ); const fieldVal = raw[operand.field]?.value ?? ""; const n = Number(fieldVal); if (Number.isNaN(n)) { throw new DmlConvertError( `\u7B97\u8853\u5F0F\u306E\u30D5\u30A3\u30FC\u30EB\u30C9 "${operand.field}" \u306E\u5024 "${fieldVal}" \u306F\u6570\u5024\u3067\u306F\u3042\u308A\u307E\u305B\u3093` ); } return n; } function deleteToGetQuery(stmt) { assertDmlWhereIsSafe(stmt.where); return { app: stmt.appId, query: whereToKintone(stmt.where), fields: ["$id"], totalCount: false }; } function deleteToDeleteBatches(appId, ids) { return chunk(ids, 100).map((batch) => ({ app: appId, ids: batch })); } function isUserType(t) { return USER_TYPES.has(t ?? ""); } function isArrayType(t) { return ARRAY_TYPES.has(t ?? ""); } function convertToDatetime(raw) { if (!raw) return raw; if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(raw)) return raw; let s = raw.replace(/\//g, "-").replace(" ", "T"); if (/T\d{2}:\d{2}$/.test(s)) s += ":00"; const d = new Date(s); if (isNaN(d.getTime())) return raw; return d.toISOString().replace(/\.\d{3}Z$/, "Z"); } function convertToDate(raw) { if (!raw) return raw; if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) return raw; return raw.replace(/\//g, "-"); } function convertString2(raw, fieldType) { if (isUserType(fieldType)) { if (raw === "") return []; return raw.split(",").map((c) => ({ code: c.trim() })); } if (isArrayType(fieldType)) { if (raw === "") return []; return raw.split(",").map((v) => v.trim()); } if (fieldType === "DATETIME") return convertToDatetime(raw); if (fieldType === "DATE") return convertToDate(raw); return raw; } function convertArray(elements, fieldType) { if (isUserType(fieldType)) return elements.map((c) => ({ code: c })); return elements; } function evalCaseResultValue(result, row, fieldType) { if (result.type === "ARRAY") { return convertArray(result.elements.map((e) => e.value), fieldType); } if (result.type === "STRING") { return convertString2(result.value, fieldType); } if (result.type === "STRING_FUNC") { return evalStringFunc(result, row); } if (result.type === "FIELD_REF" || result.type === "ARITH") { return String(evalArithExpr(result, row)); } return String(evalScalarValueExpr(result, row)); } function collectUpdateCheckTargetFields(stmt) { if (!stmt.checkGroups) return []; const targetAlias = `app${stmt.appId}`.toLowerCase(); return [...new Set(collectCheckFieldRefs(stmt.checkGroups).filter((ref) => ref.tableAlias === null || ref.tableAlias.toLowerCase() === targetAlias).map((ref) => ref.field).filter((field) => field !== "$id"))]; } function evalCaseWhenValue(expr, row, fieldType) { for (const branch of expr.branches) { if (evalWhere(branch.condition, row)) { return evalCaseResultValue(branch.result, row, fieldType); } } if (expr.elseResult !== null) { return evalCaseResultValue(expr.elseResult, row, fieldType); } return ""; } function toKintoneValue(value, fieldType) { const result = normalizeDmlSqlValue(value, fieldType); if (!result.ok) throw new DmlConvertError(result.message); return result.value; } function normalizeDmlSqlValue(value, fieldType) { try { return { ok: true, value: convertDmlSqlValue(value, fieldType) }; } catch (e) { return { ok: false, message: e instanceof Error ? e.message : String(e) }; } } function convertDmlSqlValue(value, fieldType) { switch (value.type) { case "VARIABLE": throw new DmlConvertError(`\u672A\u89E3\u6C7A\u306E\u30D0\u30C3\u30C1\u5909\u6570 @${value.name} \u304C\u3042\u308A\u307E\u3059`); case "VARIABLE_IN_LIST": throw new DmlConvertError(`\u672A\u89E3\u6C7A\u306E\u914D\u5217\u5909\u6570 @${value.name} \u304C\u3042\u308A\u307E\u3059`); case "STRING": return convertString2(value.value, fieldType); case "NUMBER": return numberLiteralText(value); case "ARRAY": return convertArray(value.elements.map((e) => e.value), fieldType); case "KINTONE_FUNC": throw new DmlConvertError( `${value.name}() \u306F INSERT / UPDATE \u306E\u5024\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093` ); case "IN_LIST": throw new DmlConvertError( "IN_LIST \u306F INSERT / UPDATE \u306E\u5024\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); case "ARITH_VALUE": throw new DmlConvertError( "\u7B97\u8853\u5F0F\u306F INSERT / UPDATE \u306E\u5024\u3068\u3057\u3066\u76F4\u63A5\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); case "CASE_VALUE": throw new DmlConvertError( "CASE WHEN \u306F INSERT / UPDATE \u306E\u5024\u3068\u3057\u3066\u76F4\u63A5\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); case "SUBQUERY_IN_LIST": throw new DmlConvertError( "IN (SELECT ...) \u306F INSERT / UPDATE \u306E\u5024\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); case "SCALAR_SUBQUERY": throw new DmlConvertError( "\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u306F INSERT / UPDATE \u306E\u5024\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093" ); } } function chunk(arr, size) { const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; } var DmlConvertError = class extends Error { constructor(message) { super(message); this.name = "DmlConvertError"; } }; // src/core/applyMultiValuePlan.ts init_define_KSQL_DOCS(); var STRING_ARRAY_TYPES = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]); var CODE_ARRAY_TYPES = /* @__PURE__ */ new Set([ "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT" ]); function argument(message) { throw new Error(`ArgumentError: ${message}`); } function buildApplyMultiValueFieldPlan(block, snapshotValue, field) { const fieldType = requireMultiValueFieldType(field.fieldType, block.field); const snapshotCodes = readSnapshotCodes(snapshotValue, fieldType, block.field); const snapshotSet = new Set(snapshotCodes); const addOrder = []; const addSet = /* @__PURE__ */ new Set(); const removeSet = /* @__PURE__ */ new Set(); for (const operation of block.operations) { const value = operation.value; if (value === "") continue; if (operation.kind === "ADD") { if (!addSet.has(value)) addOrder.push(value); addSet.add(value); } else { removeSet.add(value); } } for (const value of addSet) { if (removeSet.has(value)) { argument(`APPLY multi-value field ${block.field} has conflicting ADD and REMOVE for ${JSON.stringify(value)}.`); } } const survivorCodes = snapshotCodes.filter((value) => !removeSet.has(value)); const appendedCodes = addOrder.filter((value) => !snapshotSet.has(value)); const postImageCodes = [...survivorCodes, ...appendedCodes]; const actuallyRemoved = new Set(snapshotCodes.filter((value) => removeSet.has(value))).size; const reportedAdds = /* @__PURE__ */ new Set(); const reportedRemoves = /* @__PURE__ */ new Set(); const operations = block.operations.map((operation) => { const reported = operation.kind === "ADD" ? reportedAdds : reportedRemoves; const first = !reported.has(operation.value); reported.add(operation.value); return { kind: operation.kind, value: operation.value, changed: operation.value !== "" && first && (operation.kind === "ADD" ? !snapshotSet.has(operation.value) : snapshotSet.has(operation.value)) }; }); const postImageValue = STRING_ARRAY_TYPES.has(fieldType) ? postImageCodes : postImageCodes.map((code) => ({ code })); return { field: block.field, fieldType, operations, postImageValue, addedValues: appendedCodes.length, removedValues: actuallyRemoved, changedValues: appendedCodes.length + actuallyRemoved }; } function requireMultiValueFieldType(fieldType, field) { if (STRING_ARRAY_TYPES.has(fieldType) || CODE_ARRAY_TYPES.has(fieldType)) { return fieldType; } return argument(`APPLY multi-value target ${field} has unsupported type ${fieldType}.`); } function readSnapshotCodes(raw, fieldType, field) { if (!Array.isArray(raw)) return argument(`APPLY snapshot for ${field} must be an array.`); const codes = raw.map((item, index) => { if (STRING_ARRAY_TYPES.has(fieldType)) { if (typeof item !== "string") { return argument(`APPLY snapshot for ${field} must contain string values (item ${index + 1}).`); } return item; } if (typeof item !== "object" || item === null || typeof item.code !== "string") { return argument(`APPLY snapshot for ${field} must contain {code: string} values (item ${index + 1}).`); } return item.code; }); return [...new Set(codes.filter((code) => code !== ""))]; } // src/core/applyPatchPlanner.ts function argument2(message) { throw new Error(`ArgumentError: ${message}`); } function getApplyParentId(statement) { const where = statement.where; if (where.type !== "BINARY" || where.op !== "=" || where.left.type !== "FIELD" || where.left.tableAlias !== null || where.left.field !== "$id" || where.right.type !== "NUMBER" || !Number.isSafeInteger(where.right.value) || where.right.value <= 0) { return argument2("APPLY parent selector must be a single positive $id."); } return where.right.value; } function resolveApplyPatchMetadata(statement, fieldInfos) { const blocks = statement.applyBlocks; if (!blocks?.length) return argument2("APPLY block is missing."); const fieldsByCode = new Map(fieldInfos.map((field) => [field.code, field])); const targetTables = /* @__PURE__ */ new Map(); const targetMultiValueFields = /* @__PURE__ */ new Map(); const childrenByTable = /* @__PURE__ */ new Map(); for (const assignment of statement.assignments) { assertWritableAssignment(assignment.field, null, fieldsByCode); assertParentReferences(assignment.value, fieldsByCode); } for (const block of blocks) { if (targetTables.has(block.field) || targetMultiValueFields.has(block.field)) { argument2(`APPLY has more than one block for field ${block.field}.`); } if (statement.assignments.some((assignment) => assignment.field === block.field)) { argument2(`APPLY target ${block.field} is also assigned by parent SET.`); } const target = fieldInfos.find((field) => field.code === block.field && !field.inSubtable); if (!target) return block.targetKind === "SUBTABLE" ? argument2(`APPLY target ${block.field} is not a SUBTABLE.`) : argument2(`APPLY target ${block.field} does not exist as a top-level field.`); assertApplyTargetFieldType(block, target.fieldType); if (block.targetKind === "MULTI_VALUE") { if (target.writable === false) argument2(`APPLY target ${block.field} is not writable (${target.fieldType}).`); targetMultiValueFields.set(block.field, target); continue; } const targetTable = target; const targetChildren = new Map( fieldInfos.filter((field) => field.inSubtable && field.subtableCode === block.field).map((field) => [field.code, field]) ); targetTables.set(block.field, targetTable); childrenByTable.set(block.field, targetChildren); for (const operation of block.operations) { if (operation.kind === "PATCH") { for (const assignment of operation.assignments) { assertWritableAssignment(assignment.field, block.field, fieldsByCode, targetChildren); assertChildReferences(assignment.value, block.field, fieldsByCode, targetChildren); } if (operation.selector.kind === "WHERE") { assertChildReferences(operation.selector.where, block.field, fieldsByCode, targetChildren); } } else if (operation.kind === "APPEND") { const specified = /* @__PURE__ */ new Set(); for (const field of operation.fields) { if (specified.has(field)) argument2(`APPLY APPEND specifies child ${field} more than once.`); specified.add(field); assertWritableAssignment(field, block.field, fieldsByCode, targetChildren); } } else if (operation.kind === "REMOVE" && operation.selector.kind === "WHERE") { assertChildReferences(operation.selector.where, block.field, fieldsByCode, targetChildren); } } } return { targetTables, targetMultiValueFields, childrenByTable, fieldsByCode }; } function assertParentReferences(node, fieldsByCode) { visitFieldReferences(node, (code) => { if (code === "$id" || code === "$revision") return; const field = fieldsByCode.get(code); if (!field || field.inSubtable) argument2(`APPLY parent reference ${code} is not a top-level field.`); if (field.fieldType === "FILE") argument2(`APPLY parent FILE reference ${code} is not supported.`); }); } function assertWritableAssignment(code, table, fieldsByCode, targetChildren) { if (code.startsWith("_") || code.startsWith("$")) { argument2(`APPLY assignment target ${code} is a system field.`); } const field = table === null ? [...fieldsByCode.values()].find((item) => item.code === code && !item.inSubtable) : targetChildren?.get(code); if (!field) { const elsewhere = fieldsByCode.get(code); if (table !== null && elsewhere?.inSubtable) { argument2(`APPLY child ${code} does not belong to subtable ${table}.`); } argument2(`APPLY ${table === null ? "parent field" : "child"} ${code} does not exist.`); } if (field.fieldType === "SUBTABLE" || field.fieldType === "FILE" || field.writable === false) { argument2(`APPLY assignment target ${code} is not writable (${field.fieldType}).`); } } function assertChildReferences(node, table, fieldsByCode, targetChildren) { visitFieldReferences(node, (code) => { if (code === "_rid" || code === "_idx") return; if (targetChildren.has(code)) return; const field = fieldsByCode.get(code); if (field?.inSubtable) argument2(`APPLY child reference ${code} does not belong to subtable ${table}.`); argument2(`APPLY child reference ${code} does not exist in subtable ${table}.`); }); } function collectApplySnapshotFields(statement, fieldInfos) { const metadata = resolveApplyPatchMetadata(statement, fieldInfos); const fields = /* @__PURE__ */ new Set(["$id", "$revision"]); for (const info of fieldInfos) { if (info.inSubtable || info.fieldType === "FILE") continue; fields.add(info.code); } for (const table of metadata.targetTables.values()) fields.add(table.code); for (const assignment of statement.assignments) { visitFieldReferences(assignment.value, (code) => { const info = metadata.fieldsByCode.get(code); if (!info?.inSubtable && info?.fieldType !== "FILE") fields.add(code); }); } return [...fields]; } function flattenSubtableSnapshotRow(row, rowIndex) { const flat = { _rid: row.id ?? "", _idx: String(rowIndex) }; for (const [code, cell] of Object.entries(row.value ?? {})) { flat[code] = normalizeUnknownToString(cell?.value); } return flat; } function buildApplyPatchPlan(input) { const { statement, snapshot, fieldInfos } = input; const metadata = input.metadata ?? resolveApplyPatchMetadata(statement, fieldInfos); const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id"); const expectedParentId = getApplyParentId(statement); if (parentId !== expectedParentId) argument2(`APPLY snapshot $id ${parentId} does not match requested $id ${expectedParentId}.`); return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId); } function buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata = resolveApplyPatchMetadata(statement, fieldInfos)) { const parentIds = /* @__PURE__ */ new Set(); return snapshots.map((snapshot) => { const parentId = requirePositiveInteger(snapshot["$id"]?.value, "APPLY snapshot $id"); if (parentIds.has(parentId)) argument2(`APPLY snapshots contain duplicate parentId ${parentId}.`); parentIds.add(parentId); return buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId); }); } function buildApplyPatchPlanForSnapshot(statement, snapshot, metadata, parentId) { const revision = requirePositiveInteger(snapshot["$revision"]?.value, "APPLY snapshot $revision"); const tablePlans = []; const multiValuePlans = []; for (const block of statement.applyBlocks) { if (block.targetKind === "MULTI_VALUE") { const field = metadata.targetMultiValueFields.get(block.field); if (!field) argument2(`APPLY multi-value metadata for ${block.field} is missing.`); multiValuePlans.push(buildApplyMultiValueFieldPlan(block, snapshot[block.field]?.value, field)); continue; } const targetChildren = metadata.childrenByTable.get(block.field); const snapshotRows = readSnapshotRows(snapshot, block.field); const seenRowIds = /* @__PURE__ */ new Set(); for (const row of snapshotRows) { if (!row.id) argument2(`APPLY snapshot for ${block.field} contains a row without _rid.`); if (seenRowIds.has(row.id)) argument2(`APPLY snapshot for ${block.field} contains duplicate _rid ${row.id}.`); seenRowIds.add(row.id); } const childTypeResolver = (field) => field.field === "_rid" ? "SINGLE_LINE_TEXT" : field.field === "_idx" ? "NUMBER" : targetChildren.get(field.field)?.fieldType; const resolved = []; const appended = []; const operationPlans = []; const occupiedCells = /* @__PURE__ */ new Set(); const patchedRowIndices = /* @__PURE__ */ new Set(); const removedRowIndices = /* @__PURE__ */ new Set(); const hasRemove = block.operations.some((operation) => operation.kind === "REMOVE"); for (const [operationIndex, operation] of block.operations.entries()) { if (operation.kind === "APPEND") { const rows = buildApplyAppendRows(operation, targetChildren, block.field); operationPlans.push({ kind: "APPEND", addedRows: rows.length }); appended.push(...rows); continue; } if (operation.kind === "REMOVE") { const indices2 = resolveRemoveTargets(operation, snapshotRows, childTypeResolver, block.field); if (operation.expectRows) { assertExpectRows(operation.expectRows, indices2.length, parentId, block.field, operationIndex, operation.kind); } operationPlans.push({ kind: "REMOVE", removedRows: indices2.length }); for (const rowIndex of indices2) { const rowId = snapshotRows[rowIndex].id; if (patchedRowIndices.has(rowIndex)) { argument2(`APPLY row ${rowId} is selected by both PATCH and REMOVE.`); } if (removedRowIndices.has(rowIndex)) { argument2(`APPLY removes row ${rowId} more than once.`); } removedRowIndices.add(rowIndex); } continue; } if (operation.kind !== "PATCH") continue; const indices = resolvePatchTargets(operation, snapshotRows, childTypeResolver, block.field); if (operation.expectRows) { assertExpectRows(operation.expectRows, indices.length, parentId, block.field, operationIndex, operation.kind); } operationPlans.push({ kind: "PATCH", matchedRows: indices.length, changedRows: indices.length }); for (const rowIndex of indices) { const row = snapshotRows[rowIndex]; if (removedRowIndices.has(rowIndex)) { argument2(`APPLY row ${row.id} is selected by both PATCH and REMOVE.`); } patchedRowIndices.add(rowIndex); const flat = flattenSubtableSnapshotRow(row, rowIndex); for (const assignment of operation.assignments) { const key = `${row.id}\0${assignment.field}`; if (occupiedCells.has(key)) argument2(`APPLY patches cell ${row.id}.${assignment.field} more than once.`); occupiedCells.add(key); resolved.push({ rowIndex, field: assignment.field, value: evaluateSubtableAssignmentValue(assignment.value, flat, childTypeResolver) }); } } } const updatesByIndex = /* @__PURE__ */ new Map(); for (const cell of resolved) { const updates = updatesByIndex.get(cell.rowIndex) ?? {}; updates[cell.field] = { value: cell.value }; updatesByIndex.set(cell.rowIndex, updates); } const survivorRows = snapshotRows.flatMap( (row, index) => removedRowIndices.has(index) ? [] : [{ id: row.id, value: { ...row.value, ...updatesByIndex.get(index) ?? {} } }] ); const postImageRows = [...survivorRows, ...appended]; const base = { table: block.field, operations: operationPlans, changedSubtableRows: updatesByIndex.size + removedRowIndices.size + appended.length, deletedRows: removedRowIndices.size, snapshotRowIds: snapshotRows.map((row) => row.id), postImageRows }; if (hasRemove) { tablePlans.push({ ...base, payloadShape: "FULL_SURVIVORS", removedRowIds: snapshotRows.flatMap((row, index) => removedRowIndices.has(index) ? [row.id] : []), payloadRows: postImageRows.map((row) => ({ ...row.id === void 0 ? {} : { id: row.id }, value: row.value })) }); } else { tablePlans.push({ ...base, payloadShape: "PATCH_ONLY", payloadRows: [ ...snapshotRows.map((row, index) => { const updates = updatesByIndex.get(index); return updates ? { id: row.id, value: updates } : { id: row.id }; }), ...appended.map((row) => ({ value: row.value })) ] }); } } const parentRow = kintoneRecordToProcessRow2(snapshot); const parentValues = {}; for (const assignment of statement.assignments) { const fieldType = metadata.fieldsByCode.get(assignment.field)?.fieldType; parentValues[assignment.field] = { value: evaluateUpdateAssignmentValue(assignment.value, parentRow, fieldType, snapshot) }; } const postImage = { ...snapshot }; Object.assign(postImage, parentValues); for (const table of tablePlans) postImage[table.table] = { value: table.postImageRows }; for (const multiValue of multiValuePlans) { postImage[multiValue.field] = { value: multiValue.postImageValue }; } return { app: statement.appId, parentId, revision, parentRows: 1, changedSubtableRows: tablePlans.reduce((sum, table) => sum + table.changedSubtableRows, 0), parentValues, postImage, tables: tablePlans, multiValues: multiValuePlans }; } function assertExpectRows(guard, actual, parentId, table, operationIndex, operationKind) { const matches = guard.kind === "EXACT" ? actual === guard.count : guard.kind === "BETWEEN" ? actual >= guard.min && actual <= guard.max : guard.kind === "AT_LEAST" ? actual >= guard.count : actual <= guard.count; if (matches) return; const expected = guard.kind === "EXACT" ? `exactly ${guard.count}` : guard.kind === "BETWEEN" ? `between ${guard.min} and ${guard.max}` : guard.kind === "AT_LEAST" ? `at least ${guard.count}` : `at most ${guard.count}`; argument2( `APPLY EXPECT ROWS mismatch for parent $id ${parentId}, table ${table}, operation ${operationIndex + 1} (${operationKind}): expected ${expected}, actual ${actual}.` ); } function normalizeApplyPatchPlan(plan, normalizedRecord) { const tables = plan.tables.map((table) => { const normalizedRows = normalizedRecord[table.table]?.value; if (!Array.isArray(normalizedRows) || normalizedRows.length !== table.postImageRows.length) { return argument2(`APPLY normalized post-image for ${table.table} has an unexpected row count.`); } const payloadRows = table.payloadRows.map((payload, index) => { const normalized = normalizedRows[index]; if (!normalized?.value) return argument2(`APPLY normalized post-image for ${table.table} row ${index + 1} has no value.`); if (payload.id === void 0) return { value: normalized.value }; if (payload.value === void 0) return { id: payload.id }; return { id: payload.id, value: Object.fromEntries(Object.keys(payload.value).map((field) => [field, normalized.value[field]])) }; }); return { ...table, payloadRows, postImageRows: normalizedRows }; }); const parentValues = Object.fromEntries(Object.keys(plan.parentValues).map((field) => [ field, normalizedRecord[field] ?? plan.parentValues[field] ])); const multiValues = plan.multiValues.map((multiValue) => { const normalized = normalizedRecord[multiValue.field]?.value; if (!Array.isArray(normalized)) { return argument2(`APPLY normalized post-image for ${multiValue.field} is not an array.`); } return { ...multiValue, postImageValue: normalized }; }); return { ...plan, parentValues, tables, multiValues, postImage: normalizedRecord }; } function buildApplyAppendRows(operation, children, table) { return operation.values.map((row) => ({ value: buildAppendValue(operation, row, children, table) })); } function buildAppendValue(operation, row, children, table) { if (row.length !== operation.fields.length) { return argument2(`APPLY APPEND for ${table} has ${row.length} values for ${operation.fields.length} fields.`); } const specified = new Map(operation.fields.map((field, index) => [field, row[index]])); const value = {}; for (const field of children.values()) { if (field.fieldType === "FILE" || field.writable === false) continue; const sqlValue = specified.get(field.code); value[field.code] = { value: sqlValue === void 0 ? appendDefaultValue(field) : sqlValue.type === "CASE_VALUE" ? evalCaseWhenValue(sqlValue.expr, {}, field.fieldType) : toKintoneValue(sqlValue, field.fieldType) }; } return value; } function appendDefaultValue(field) { if (field.defaultValue !== void 0 && field.defaultValue !== null) return field.defaultValue; return ["CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(field.fieldType) ? [] : ""; } function resolvePatchTargets(operation, rows, resolveFieldType, table) { return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table); } function resolveRemoveTargets(operation, rows, resolveFieldType, table) { return resolveSelectorTargets(operation.selector, rows, resolveFieldType, table); } function resolveSelectorTargets(selector, rows, resolveFieldType, table) { if (selector.kind === "ALL_ROWS") return rows.map((_, index) => index); const where = selector.where; const indices = rows.flatMap( (row, index) => evalWhere(where, flattenSubtableSnapshotRow(row, index), resolveFieldType) ? [index] : [] ); const requestedRid = exactRidSelectorValue(where); if (requestedRid !== null && indices.length === 0) { argument2(`APPLY _rid ${requestedRid} does not exist in snapshot table ${table}.`); } const requestedIdx = exactIdxSelectorValue(where); if (requestedIdx !== null && indices.length === 0) { argument2(`APPLY _idx ${requestedIdx} does not exist in snapshot table ${table}.`); } return indices; } function exactRidSelectorValue(where) { if (where.type !== "BINARY" || where.op !== "=" || where.left.type !== "FIELD" || where.left.tableAlias !== null || where.left.field !== "_rid") return null; if (where.right.type === "STRING") return where.right.value; if (where.right.type === "NUMBER") return where.right.raw ?? String(where.right.value); return null; } function exactIdxSelectorValue(where) { if (where.type !== "BINARY" || where.op !== "=" || where.left.type !== "FIELD" || where.left.tableAlias !== null || where.left.field !== "_idx" || where.right.type !== "NUMBER") { return null; } return Number.isSafeInteger(where.right.value) && where.right.value >= 0 ? where.right.value : null; } function readSnapshotRows(snapshot, table) { const raw = snapshot[table]?.value; if (!Array.isArray(raw)) return argument2(`APPLY snapshot field ${table} is not a subtable value.`); return raw.map((row) => { const item = row; return { id: typeof item.id === "string" ? item.id : "", value: item.value && typeof item.value === "object" ? item.value : {} }; }); } function requirePositiveInteger(value, label) { const n = Number(value); if (!Number.isSafeInteger(n) || n <= 0) argument2(`${label} must be a positive integer.`); return n; } function kintoneRecordToProcessRow2(record2) { const row = {}; for (const [code, cell] of Object.entries(record2)) { row[code] = normalizeUnknownToString(cell?.value); } return row; } function normalizeUnknownToString(value) { if (value === null || value === void 0) return ""; if (typeof value === "string") return value; if (typeof value === "number" || typeof value === "boolean") return String(value); try { return JSON.stringify(value); } catch { return String(value); } } function visitFieldReferences(node, visit) { if (Array.isArray(node)) { node.forEach((item2) => visitFieldReferences(item2, visit)); return; } if (node === null || typeof node !== "object") return; const item = node; if ((item["type"] === "FIELD" || item["type"] === "FIELD_REF") && typeof item["field"] === "string") { visit(item["field"]); } for (const value of Object.values(item)) visitFieldReferences(value, visit); } // src/core/applyPatchPrepare.ts init_define_KSQL_DOCS(); // src/converter/applyPatchToKintone.ts init_define_KSQL_DOCS(); var KINTONE_PUT_RECORD_LIMIT = 100; function argument3(message) { throw new Error(`ArgumentError: ${message}`); } function requireRevision(record2) { const revision = Number(record2["$revision"]?.value); if (!Number.isSafeInteger(revision) || revision <= 0) { return argument3("APPLY snapshot $revision must be a positive integer."); } return revision; } function applyPatchPlanToKintone(plan) { if (!Number.isSafeInteger(plan.parentId) || plan.parentId <= 0) { return argument3("APPLY plan parentId must be a positive integer."); } if (!Number.isSafeInteger(plan.revision) || plan.revision <= 0) { return argument3("APPLY plan revision must be a positive integer."); } const record2 = { ...plan.parentValues }; const seenFields = new Set(Object.keys(record2)); for (const multiValue of plan.multiValues) { if (seenFields.has(multiValue.field)) { argument3(`APPLY plan contains duplicate top-level field ${multiValue.field}.`); } seenFields.add(multiValue.field); record2[multiValue.field] = { value: multiValue.postImageValue }; } const seenTables = /* @__PURE__ */ new Set(); for (const table of plan.tables) { if (seenFields.has(table.table)) argument3(`APPLY plan contains duplicate top-level field ${table.table}.`); if (seenTables.has(table.table)) argument3(`APPLY plan contains duplicate table ${table.table}.`); seenTables.add(table.table); seenFields.add(table.table); assertTablePlan(table); record2[table.table] = { value: table.payloadRows }; } return { app: plan.app, records: [{ id: plan.parentId, revision: plan.revision, record: record2 }] }; } function applyPatchPlansToKintoneBatches(prepared) { if (prepared.records.length === 0) return []; const app = prepared.plans[0]?.app; if (!Number.isSafeInteger(app) || app <= 0 || prepared.plans.length !== prepared.records.length) { return argument3("prepared APPLY plans and records must have the same positive-app parent count."); } const batches = []; for (let index = 0; index < prepared.records.length; index += KINTONE_PUT_RECORD_LIMIT) { batches.push({ app, records: prepared.records.slice(index, index + KINTONE_PUT_RECORD_LIMIT) }); } return batches; } function assertTablePlan(table) { const snapshotIds = assertUniqueIds(table.snapshotRowIds, `${table.table} snapshot`); const payloadIds = table.payloadRows.flatMap((row) => row.id === void 0 ? [] : [row.id]); for (const row of table.payloadRows) { if (row.id === void 0 && row.value === void 0) { argument3(`APPLY ${table.payloadShape} table ${table.table} contains an APPEND row without value.`); } } assertUniqueIds(payloadIds, `${table.table} payload`); if (table.payloadShape === "PATCH_ONLY") { if (table.operations.some((operation) => operation.kind === "REMOVE")) { argument3(`APPLY PATCH_ONLY table ${table.table} cannot contain REMOVE.`); } const payloadPrefixIds2 = table.payloadRows.slice(0, snapshotIds.length).map((row) => row.id ?? ""); assertSameOrderedIds( snapshotIds, payloadPrefixIds2, `APPLY PATCH_ONLY table ${table.table} must retain every snapshot row id in order.` ); if (table.payloadRows.slice(snapshotIds.length).some((row) => row.id !== void 0)) { argument3(`APPLY PATCH_ONLY table ${table.table} must place every APPEND row after snapshot rows.`); } const postPrefixIds = table.postImageRows.slice(0, snapshotIds.length).map((row) => row.id ?? ""); assertSameOrderedIds( snapshotIds, postPrefixIds, `APPLY PATCH_ONLY table ${table.table} post-image must retain every snapshot row id in order.` ); if (table.postImageRows.slice(snapshotIds.length).some((row) => row.id !== void 0)) { argument3(`APPLY PATCH_ONLY table ${table.table} post-image must place every APPEND row after snapshot rows.`); } return; } if (!table.operations.some((operation) => operation.kind === "REMOVE")) { argument3(`APPLY FULL_SURVIVORS table ${table.table} requires a REMOVE operation.`); } const removed = assertUniqueIds(table.removedRowIds, `${table.table} removed`); if (table.deletedRows !== removed.length) { argument3(`APPLY FULL_SURVIVORS table ${table.table} deleted row count does not match removed ids.`); } if (table.payloadRows.length !== table.postImageRows.length) { argument3(`APPLY FULL_SURVIVORS table ${table.table} payload/post-image row counts must match.`); } const survivorIds = table.postImageRows.flatMap((row) => row.id === void 0 ? [] : [row.id]); const removedSet = new Set(removed); const survivorSet = new Set(survivorIds); for (const id of removed) { if (survivorSet.has(id)) argument3(`APPLY FULL_SURVIVORS table ${table.table} has intersecting survivor/removed id ${id}.`); } const expectedSurvivorIds = snapshotIds.filter((id) => !removedSet.has(id)); assertSameOrderedIds( expectedSurvivorIds, survivorIds, `APPLY FULL_SURVIVORS table ${table.table} must retain every survivor in snapshot order.` ); const payloadPrefixIds = table.payloadRows.slice(0, survivorIds.length).map((row) => row.id ?? ""); assertSameOrderedIds( survivorIds, payloadPrefixIds, `APPLY FULL_SURVIVORS table ${table.table} payload must enumerate every survivor in order.` ); if (table.payloadRows.slice(survivorIds.length).some((row) => row.id !== void 0) || table.postImageRows.slice(survivorIds.length).some((row) => row.id !== void 0)) { argument3(`APPLY FULL_SURVIVORS table ${table.table} must place every APPEND row after survivors.`); } if (table.payloadRows.some((row) => row.value === void 0)) { argument3(`APPLY FULL_SURVIVORS table ${table.table} requires values for every survivor.`); } if (table.payloadRows.some((row, index) => !deepEqual(row.value, table.postImageRows[index]?.value))) { argument3(`APPLY FULL_SURVIVORS table ${table.table} payload must contain every post-image child value.`); } const partition = /* @__PURE__ */ new Set([...survivorIds, ...removed]); if (partition.size !== snapshotIds.length || snapshotIds.some((id) => !partition.has(id))) { argument3(`APPLY FULL_SURVIVORS table ${table.table} does not partition every snapshot row.`); } } function assertUniqueIds(ids, label) { const out = [...ids]; const seen = /* @__PURE__ */ new Set(); for (const id of out) { if (!id) argument3(`APPLY ${label} contains an empty row id.`); if (seen.has(id)) argument3(`APPLY ${label} contains duplicate row id ${id}.`); seen.add(id); } return out; } function assertSameOrderedIds(actual, expected, message) { if (actual.length !== expected.length || actual.some((id, index) => id !== expected[index])) { argument3(message); } } function deepEqual(left, right) { if (Object.is(left, right)) return true; if (Array.isArray(left) || Array.isArray(right)) { return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => deepEqual(value, right[index])); } if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false; const leftRecord = left; const rightRecord = right; const leftKeys = Object.keys(leftRecord); const rightKeys = Object.keys(rightRecord); return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && deepEqual(leftRecord[key], rightRecord[key])); } // src/core/postImageValidation.ts init_define_KSQL_DOCS(); // src/core/dmlValidation.ts init_define_KSQL_DOCS(); // src/core/numberPrecision.ts init_define_KSQL_DOCS(); function parseIntegerSetting(value, name, min, max) { if (typeof value !== "string" || !/^\d+$/.test(value)) { throw new Error(`SettingsError: numberPrecision.${name} must be an integer string.`); } let parsed = 0; for (const digit of value) parsed = parsed * 10 + digit.charCodeAt(0) - 48; if (parsed < min || parsed > max) { throw new Error(`SettingsError: numberPrecision.${name} must be between ${min} and ${max}.`); } return parsed; } function parseNumberPrecisionSettings(response) { const raw = response.numberPrecision; if (raw === void 0 || raw === null || typeof raw !== "object") { throw new Error("SettingsError: numberPrecision is missing from app settings."); } const digits = parseIntegerSetting(raw.digits, "digits", 1, 30); const decimalPlaces = parseIntegerSetting(raw.decimalPlaces, "decimalPlaces", 0, 10); const roundingMode = raw.roundingMode; if (roundingMode !== "HALF_EVEN" && roundingMode !== "UP" && roundingMode !== "DOWN") { throw new Error("SettingsError: numberPrecision.roundingMode is unsupported."); } return { digits, decimalPlaces, roundingMode }; } function exactDecimalDigitCounts(value) { if (value.sign === 0) return { integerDigits: 0, fractionDigits: 0 }; return { integerDigits: Math.max(value.coefficient.length - value.scale, 0), fractionDigits: Math.max(value.scale, 0) }; } // src/core/dmlValidation.ts var ARRAY_TYPES2 = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]); var CHOICE_TYPES = /* @__PURE__ */ new Set(["DROP_DOWN", "RADIO_BUTTON", "CHECK_BOX", "MULTI_SELECT"]); function validateAndNormalizeDmlValue(raw, field, numberPrecision) { if (field.fieldType === "DATE" || field.fieldType === "TIME" || field.fieldType === "DATETIME") { const original = rawScalarText(raw); if (original !== "" && !isValidTemporalInput(original, field.fieldType)) { return { ok: false, code: "ERR_TYPE_DATE", message: `${field.code} \u306E\u65E5\u4ED8\u30FB\u6642\u523B\u5F62\u5F0F\u304C\u4E0D\u6B63\u3067\u3059` }; } } let value; try { value = normalizeRaw(raw, field.fieldType); } catch (e) { const message = e instanceof Error ? e.message : String(e); return { ok: false, code: typeCode(field.fieldType), message }; } if (field.required && isEmpty(value)) { return { ok: false, code: "ERR_REQUIRED", message: `${field.code} \u306F\u5FC5\u9808\u3067\u3059` }; } if (!isEmpty(value) && field.fieldType === "NUMBER") { const text = String(value); const decimal = parseExactDecimal(text); if (decimal === null) { return { ok: false, code: "ERR_TYPE_NUMBER", message: `${field.code} \u306F\u6570\u5024\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044` }; } if (field.minValue != null && compareDecimal(text, field.minValue) < 0) { return { ok: false, code: "ERR_RANGE_MIN", message: `${field.code} \u306F ${field.minValue} \u4EE5\u4E0A\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044` }; } if (field.maxValue != null && compareDecimal(text, field.maxValue) > 0) { return { ok: false, code: "ERR_RANGE_MAX", message: `${field.code} \u306F ${field.maxValue} \u4EE5\u4E0B\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044` }; } if (numberPrecision !== void 0) { const { integerDigits } = exactDecimalDigitCounts(decimal); const integerBudget = numberPrecision.digits - numberPrecision.decimalPlaces; if (integerDigits > integerBudget) { return { ok: false, code: "ERR_NUMBER_INTEGER_DIGITS", message: `${field.code} \u306E\u6574\u6570\u90E8\u306F ${integerDigits} \u6841\u3067\u3059\u3002\u8A31\u5BB9\u306F ${integerBudget} \u6841\u307E\u3067\u3067\u3059 (digits=${numberPrecision.digits}, decimalPlaces=${numberPrecision.decimalPlaces})` }; } } } if (!isEmpty(value) && (field.fieldType === "DATE" || field.fieldType === "TIME" || field.fieldType === "DATETIME")) { if (!isValidTemporal(String(value), field.fieldType)) { return { ok: false, code: "ERR_TYPE_DATE", message: `${field.code} \u306E\u65E5\u4ED8\u30FB\u6642\u523B\u5F62\u5F0F\u304C\u4E0D\u6B63\u3067\u3059` }; } } if (typeof value === "string") { const length = value.length; const min = field.minLength == null ? null : Number(field.minLength); const max = field.maxLength == null ? null : Number(field.maxLength); if (Number.isFinite(min) && length < min) { return { ok: false, code: "ERR_LENGTH_MIN", message: `${field.code} \u306F ${min} \u6587\u5B57\u4EE5\u4E0A\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044` }; } if (Number.isFinite(max) && length > max) { return { ok: false, code: "ERR_LENGTH_MAX", message: `${field.code} \u306F ${max} \u6587\u5B57\u4EE5\u4E0B\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044` }; } } if (!isEmpty(value) && CHOICE_TYPES.has(field.fieldType) && field.optionOrder) { const selected = Array.isArray(value) ? value.map(String) : [String(value)]; if (selected.some((choice) => !(choice in field.optionOrder))) { return { ok: false, code: "ERR_CHOICE_INVALID", message: `${field.code} \u306B\u5B9A\u7FA9\u5916\u306E\u9078\u629E\u80A2\u304C\u3042\u308A\u307E\u3059` }; } } return { ok: true, value }; } function rawScalarText(raw) { if (raw == null) return ""; if (isSqlValue(raw) && raw.type === "NUMBER") return numberLiteralText(raw); if (isSqlValue(raw) && raw.type === "STRING") return raw.value; return typeof raw === "string" || typeof raw === "number" ? String(raw) : ""; } function isValidTemporalInput(value, type) { if (type === "DATE") return isValidTemporal(value.replace(/\//g, "-"), "DATE"); if (type === "TIME") return isValidTemporal(value, "TIME"); let normalized = value.replace(/\//g, "-").replace(" ", "T"); if (/T\d{2}:\d{2}$/.test(normalized)) normalized += ":00"; if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(normalized)) { return isValidTemporal(normalized.slice(0, 10), "DATE") && isValidTemporal(normalized.slice(11), "TIME"); } return isValidTemporal(normalized, "DATETIME"); } function normalizeRaw(raw, fieldType) { if (isSqlValue(raw)) { const normalized = normalizeDmlSqlValue(raw, fieldType); if (!normalized.ok) throw new Error(normalized.message); return normalized.value; } if (Array.isArray(raw)) return raw.map((v) => typeof v === "object" && v !== null && "code" in v ? String(v.code) : String(v)); const text = raw == null ? "" : String(raw); if (ARRAY_TYPES2.has(fieldType)) { if (text === "") return []; try { const parsed = JSON.parse(text); if (Array.isArray(parsed)) return parsed.map(String); } catch { } return text.split(",").map((v) => v.trim()); } return text; } function isSqlValue(value) { return typeof value === "object" && value !== null && typeof value.type === "string"; } function isEmptyDmlValue(value) { if (value == null || value === "") return true; if (Array.isArray(value)) return value.length === 0; if (isSqlValue(value)) { if (value.type === "STRING") return value.value === ""; if (value.type === "ARRAY") return value.elements.length === 0; } return false; } function isEmpty(value) { return value === "" || Array.isArray(value) && value.length === 0; } function typeCode(type) { return type === "NUMBER" ? "ERR_TYPE_NUMBER" : "ERR_TYPE_DATE"; } function isValidTemporal(value, type) { if (type === "TIME") { const m2 = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(value); return m2 !== null && Number(m2[1]) <= 23 && Number(m2[2]) <= 59 && Number(m2[3] ?? 0) <= 59; } const datePart = type === "DATE" ? value : value.slice(0, 10); const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(datePart); if (!m) return false; const year = Number(m[1]); const month = Number(m[2]); const day = Number(m[3]); const date5 = new Date(Date.UTC(year, month - 1, day)); if (date5.getUTCFullYear() !== year || date5.getUTCMonth() !== month - 1 || date5.getUTCDate() !== day) return false; if (type === "DATE") return true; const timePart = value.slice(11, value.endsWith("Z") ? -1 : value.length - 6).replace(/\.\d+$/, ""); return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value) && isValidTemporal(timePart, "TIME"); } // src/core/dmlValidationCandidates.ts init_define_KSQL_DOCS(); var VALIDATION_META_COLUMNS = [ "$err_statement", "$err_operation", "$err_row", "$err_field", "$err_code", "$err_message", "$err_value", "$err_subtable", "$err_subrow", "$err_subrow_id" ]; function materializeDmlUpdateModeSparseRecords(candidates, targetFields, fieldInfos) { const infoByCode = new Map(fieldInfos.map((field) => [field.code, field])); for (const candidate of candidates) { if (candidate.mode !== "update") continue; candidate.record ??= {}; for (const code of targetFields) { if (!candidate.payload.has(code)) continue; const original = candidate.payload.get(code); const type = infoByCode.get(code).fieldType; const preserveCodes = ["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(type) && Array.isArray(original) && original.every((item) => typeof item === "object" && item !== null && "code" in item); let normalized = original; try { normalized = normalizeRaw(original, type); } catch { } candidate.record[code] = { value: preserveCodes ? original : normalized }; } } } function validateDmlCandidates(candidates, operation, payloadFields, targetFields, fieldInfos, statementNumber, numberPrecision, checkGroups = [], validateMissingCreateFields = true, includePreErrors = true, validationOptions = {}) { const infoByCode = new Map(fieldInfos.map((field) => [field.code, field])); const errors = []; const invalid = /* @__PURE__ */ new Set(); const candidateResults = []; if (validationOptions.validateUpdateBuiltIns === false) { materializeDmlUpdateModeSparseRecords(candidates, targetFields, fieldInfos); } let firstEvaluationError; for (const candidate of candidates) { candidate.record ??= {}; const preErrors = includePreErrors ? [...candidate.preErrors] : []; const builtInErrors = []; const checkErrors = []; const validateBuiltIns = candidate.mode === "create" || validationOptions.validateUpdateBuiltIns !== false; for (const code of targetFields) { if (!candidate.payload.has(code)) continue; const original = candidate.payload.get(code); const type = infoByCode.get(code).fieldType; const preserveCodes = ["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(type) && Array.isArray(original) && original.every((item) => typeof item === "object" && item !== null && "code" in item); if (!validateBuiltIns) continue; const result = validateAndNormalizeDmlValue(original, infoByCode.get(code), numberPrecision); if (!result.ok) builtInErrors.push({ field: code, code: result.code, message: result.message }); else candidate.record[code] = { value: preserveCodes ? original : result.value }; } if (validateMissingCreateFields && candidate.mode === "create") { for (const info of fieldInfos) { if (info.inSubtable) continue; if (candidate.payload.has(info.code)) continue; const emptyDefault = isEmptyDmlValue(info.defaultValue); if (!emptyDefault) { const defaultResult = validateAndNormalizeDmlValue(info.defaultValue, info, numberPrecision); if (!defaultResult.ok) builtInErrors.push({ field: info.code, code: defaultResult.code, message: `\u65E2\u5B9A\u5024: ${defaultResult.message}` }); } else { const emptyResult = validateAndNormalizeDmlValue("", info, numberPrecision); if (!emptyResult.ok) { builtInErrors.push({ field: info.code, code: emptyResult.code, message: emptyResult.message }); } else if (info.required) { builtInErrors.push({ field: info.code, code: "ERR_REQUIRED", message: `${info.code} \u306F\u5FC5\u9808\u3067\u3059` }); } } } } if (checkGroups.length > 0) { const row = candidate.evaluationRow ?? Object.fromEntries( [...candidate.payload].map(([field, value]) => [field, renderValidationValue(value)]) ); const types = candidate.evaluationFieldTypes; const resolveType = (field) => { const qualified = field.tableAlias ? `${field.tableAlias}.${field.field}` : field.field; return types?.get(qualified) ?? types?.get(field.field); }; try { for (const custom2 of evaluateCustomChecks(checkGroups, row, resolveType)) { checkErrors.push({ field: "", code: "ERR_CHECK", message: custom2.message }); } } catch (error51) { firstEvaluationError ??= error51; } } const materializeErrors = (source) => source.map((error51) => { const row = {}; for (const field of payloadFields) row[field] = renderValidationValue(candidate.payload.get(field)); row["$err_statement"] = String(statementNumber); row["$err_operation"] = operation; row["$err_row"] = String(candidate.rowNumber); row["$err_field"] = error51.field; row["$err_code"] = error51.code; row["$err_message"] = error51.message; row["$err_value"] = ""; row["$err_subtable"] = ""; row["$err_subrow"] = ""; row["$err_subrow_id"] = ""; return row; }); const materialized = { rowNumber: candidate.rowNumber, preErrors: materializeErrors(preErrors), builtInErrors: materializeErrors(builtInErrors), checkErrors: materializeErrors(checkErrors) }; candidateResults.push(materialized); const rowErrors = [...materialized.preErrors, ...materialized.builtInErrors, ...materialized.checkErrors]; if (rowErrors.length > 0) invalid.add(candidate.rowNumber); errors.push(...rowErrors); } if (firstEvaluationError !== void 0) throw firstEvaluationError; return { errors, invalidRows: invalid.size, invalidRowNumbers: invalid, candidateResults }; } function renderValidationValue(value) { if (value == null) return ""; if (typeof value === "object" && "type" in value) { const sql = value; if (sql.type === "NUMBER") return sql.raw ?? String(sql.value ?? ""); if (sql.type === "STRING") return String(sql.value ?? ""); if (sql.type === "ARRAY") return JSON.stringify(sql.elements?.map((e) => e.value) ?? []); } if (Array.isArray(value)) return JSON.stringify(value); return String(value); } // src/core/existingRecordValidation.ts init_define_KSQL_DOCS(); function buildValidationFieldMetadataIndex(fieldInfos) { const topLevel = fieldInfos.filter((field) => !field.inSubtable); const childrenByTable = /* @__PURE__ */ new Map(); for (const field of fieldInfos) { if (!field.inSubtable || !field.subtableCode) continue; const children = childrenByTable.get(field.subtableCode) ?? []; children.push(field); childrenByTable.set(field.subtableCode, children); } return { topLevel, topByCode: new Map(topLevel.map((field) => [field.code, field])), childrenByTable }; } function hasAuditableConstraint(field) { return field.required === true || field.minValue !== void 0 || field.maxValue !== void 0 || field.minLength !== void 0 || field.maxLength !== void 0 || field.optionOrder !== void 0; } function isExistingValidationAuditable(field) { return field.fieldType === "NUMBER" || hasAuditableConstraint(field); } function buildValidationCellLocator(subtable, rowIndex, row) { return { subtable, subrow: rowIndex + 1, subrowId: String(row.id ?? "") }; } function resolveExistingValidationTargets(stmt, fieldInfos) { const { topByCode, childrenByTable } = buildValidationFieldMetadataIndex(fieldInfos); const auditable = isExistingValidationAuditable; if (stmt.targets === void 0) return [ ...fieldInfos.filter((field) => !field.inSubtable && field.fieldType !== "SUBTABLE" && auditable(field)), ...fieldInfos.filter((field) => field.inSubtable && !!field.subtableCode && auditable(field)) ].map((field) => ({ field, ...field.subtableCode ? { subtableCode: field.subtableCode } : {} })); const result = []; const seen = /* @__PURE__ */ new Set(); const add = (field, subtableCode) => { const key = subtableCode ? `${subtableCode}\0${field.code}` : field.code; if (seen.has(key)) throw new Error(`ArgumentError: VALIDATE \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${field.code} \u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059\u3002`); seen.add(key); if (!auditable(field)) throw new Error(`ArgumentError: VALIDATE \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${field.code} \u306B\u306F\u76E3\u67FB\u53EF\u80FD\u306A\u5236\u7D04\u304C\u3042\u308A\u307E\u305B\u3093\u3002`); result.push({ field, ...subtableCode ? { subtableCode } : {} }); }; for (const target of stmt.targets) { if (target.kind === "SUBTABLE") { const children = childrenByTable.get(target.subtableCode); if (!children) throw new Error(`ArgumentError: VALIDATE \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB ${target.subtableCode} \u306F\u5B58\u5728\u3057\u307E\u305B\u3093\u3002`); if (target.children.length === 0) throw new Error(`ArgumentError: VALIDATE \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB ${target.subtableCode} \u306B\u306F1\u3064\u4EE5\u4E0A\u306E\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u5FC5\u8981\u3067\u3059\u3002`); for (const code2 of target.children) { const child = children.find((field) => field.code === code2); if (!child) { const belongsElsewhere = [...childrenByTable.entries()].some(([table, fields]) => table !== target.subtableCode && fields.some((field) => field.code === code2)); throw new Error(belongsElsewhere ? `ArgumentError: VALIDATE \u306E\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${code2} \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB ${target.subtableCode} \u306B\u5C5E\u3057\u3066\u3044\u307E\u305B\u3093\u3002` : `ArgumentError: VALIDATE \u306E\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${code2} \u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB ${target.subtableCode} \u306B\u5B58\u5728\u3057\u307E\u305B\u3093\u3002`); } add(child, target.subtableCode); } continue; } const code = target.field; if (code === "$id") throw new Error("ArgumentError: VALIDATE \u3067\u306F\u30B7\u30B9\u30C6\u30E0\u30D5\u30A3\u30FC\u30EB\u30C9 $id \u3092\u76E3\u67FB\u3067\u304D\u307E\u305B\u3093\u3002"); const top = topByCode.get(code); if (top?.fieldType === "SUBTABLE") { const children = (childrenByTable.get(code) ?? []).filter(auditable); if (children.length === 0) throw new Error(`ArgumentError: VALIDATE \u306E\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB ${code} \u306B\u306F\u76E3\u67FB\u53EF\u80FD\u306A\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u3042\u308A\u307E\u305B\u3093\u3002`); children.forEach((child) => add(child, code)); continue; } if (top) { add(top); continue; } if ([...childrenByTable.values()].some((children) => children.some((field) => field.code === code))) { throw new Error(`ArgumentError: VALIDATE \u306E\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${code} \u306F\u6240\u6709\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u3092\u542B\u3080 T(${code}) \u5F62\u5F0F\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`); } throw new Error(`ArgumentError: VALIDATE \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${code} \u306F\u5B58\u5728\u3057\u307E\u305B\u3093\u3002`); } return result; } function renderExistingValidationValue(raw, fieldType) { return isEmptyDmlValue(raw) ? "" : renderValidationValue(normalizeRaw(raw, fieldType)); } // src/core/postImageValidation.ts var NON_AUDIT_SYSTEM_TYPES = /* @__PURE__ */ new Set([ "CALC", "RECORD_NUMBER", "CREATOR", "CREATED_TIME", "MODIFIER", "UPDATED_TIME", "STATUS", "STATUS_ASSIGNEE", "CATEGORY", "REFERENCE_TABLE" ]); var POST_IMAGE_VALIDATION_SUFFIX_COLUMNS = VALIDATION_META_COLUMNS; function buildPostImageFieldIndex(fieldInfos, payloadFields = ["$id"]) { const metadata = buildValidationFieldMetadataIndex(fieldInfos); const topLevel = metadata.topLevel.filter((field) => field.fieldType !== "SUBTABLE" && field.fieldType !== "FILE" && !NON_AUDIT_SYSTEM_TYPES.has(field.fieldType)); const subtables = /* @__PURE__ */ new Map(); for (const [tableCode, fields] of metadata.childrenByTable) { subtables.set(tableCode, fields.filter((field) => field.fieldType !== "FILE")); } return { topLevel, subtables, payloadFields: ["$id", ...new Set(payloadFields.filter((field) => field !== "$id"))] }; } function postImageNeedsNumberPrecision(record2, fieldIndex) { if (fieldIndex.topLevel.some((field) => field.fieldType === "NUMBER" && field.code in record2)) return true; for (const [tableCode, children] of fieldIndex.subtables) { if (!children.some((field) => field.fieldType === "NUMBER")) continue; const rows = record2[tableCode]?.value; if (!Array.isArray(rows)) continue; for (const row of rows) { const values = row?.value; if (children.some((field) => field.fieldType === "NUMBER" && !!values && field.code in values)) return true; } } return false; } function validatePostImage(record2, fieldIndex, numberPrecision, statementNumber, parentRowNumber = 1, operation = "UPDATE") { const normalizedRecord = cloneRecord(record2); const errors = []; const invalidRowNumbers = /* @__PURE__ */ new Set(); const columns = [...fieldIndex.payloadFields, ...POST_IMAGE_VALIDATION_SUFFIX_COLUMNS]; const parentId = renderValidationValue(record2["$id"]?.value); const appendError = (field, raw, validation, locator) => { invalidRowNumbers.add(parentRowNumber); const row = {}; for (const code of fieldIndex.payloadFields) { row[code] = code === "$id" ? parentId : renderValidationValue(record2[code]?.value); } row["$err_statement"] = String(statementNumber); row["$err_operation"] = operation; row["$err_row"] = String(parentRowNumber); row["$err_field"] = field.code; row["$err_code"] = validation.code; row["$err_message"] = validation.message; row["$err_value"] = renderExistingValidationValue(raw, field.fieldType); row["$err_subtable"] = locator?.subtable ?? ""; row["$err_subrow"] = locator ? String(locator.subrow) : ""; row["$err_subrow_id"] = locator?.subrowId ?? ""; errors.push(row); }; for (const field of fieldIndex.topLevel) { const raw = record2[field.code]?.value; const result = validateAndNormalizeDmlValue(raw, field, numberPrecision); if (!result.ok) appendError(field, raw, result); else normalizedRecord[field.code] = { value: preserveCodeObjects(raw, field.fieldType, result.value) }; } for (const [tableCode, children] of fieldIndex.subtables) { const sourceRows = record2[tableCode]?.value; if (!Array.isArray(sourceRows)) continue; const normalizedRows = normalizedRecord[tableCode]?.value; for (let rowIndex = 0; rowIndex < sourceRows.length; rowIndex++) { const sourceRow = sourceRows[rowIndex]; const normalizedRow = normalizedRows[rowIndex]; for (const field of children) { const raw = sourceRow.value?.[field.code]?.value; const result = validateAndNormalizeDmlValue(raw, field, numberPrecision); if (!result.ok) appendError(field, raw, result, buildValidationCellLocator(tableCode, rowIndex, sourceRow)); else { normalizedRow.value ??= {}; normalizedRow.value[field.code] = { value: preserveCodeObjects(raw, field.fieldType, result.value) }; } } } } return { normalizedRecord, errors, columns, invalidRows: invalidRowNumbers.size, invalidRowNumbers, errorCount: errors.length }; } function preserveCodeObjects(raw, fieldType, normalized) { return ["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(fieldType) && Array.isArray(raw) && raw.every((item) => typeof item === "object" && item !== null && "code" in item) ? raw : normalized; } function cloneRecord(record2) { const clone2 = {}; for (const [code, cell] of Object.entries(record2)) { const value = cell?.value; clone2[code] = { value: Array.isArray(value) ? value.map((item) => { if (item === null || typeof item !== "object") return item; const row = item; if (!row.value) return { ...row }; return { ...row, value: Object.fromEntries(Object.entries(row.value).map(([field, child]) => [field, { ...child }])) }; }) : value }; } return clone2; } // src/core/applyPatchPrepare.ts async function prepareApplyPatchWrite(input) { const { statement, snapshots, fieldInfos, metadata, dmlMaxRows, dmlMaxSubtableRows, statementNumber = 1 } = input; assertPositiveLimit(dmlMaxRows, "dmlMaxRows"); assertPositiveLimit(dmlMaxSubtableRows, "dmlMaxSubtableRows"); for (const snapshot of snapshots) requireRevision(snapshot); const rawPlans = buildApplyPatchPlans(statement, snapshots, fieldInfos, metadata); const fieldIndex = buildPostImageFieldIndex( fieldInfos, statement.assignments.map((assignment) => assignment.field) ); const needsNumberPrecision = rawPlans.some( (plan) => postImageNeedsNumberPrecision(plan.postImage, fieldIndex) ); if (needsNumberPrecision && !input.loadNumberPrecision) { throw new Error("InternalError: APPLY number precision loader is required for NUMBER post-images."); } const numberPrecision = needsNumberPrecision ? await input.loadNumberPrecision() : void 0; const validationResults = rawPlans.map( (plan, index) => validatePostImage( plan.postImage, fieldIndex, numberPrecision, statementNumber, input.parentRowNumbers?.[index] ?? index + 1 ) ); if (!statement.validateOnly) { const errors = validationResults.flatMap((validation) => validation.errors); if (errors.length > 0) { throw new Error(`ArgumentError: APPLY post-image validation failed: ${JSON.stringify({ columns: validationResults[0]?.columns ?? [], errors })}`); } } const parentRows = rawPlans.length; const subtableRows = rawPlans.reduce((sum, plan) => sum + plan.changedSubtableRows, 0); const wouldExceed = parentRows > dmlMaxRows || subtableRows > dmlMaxSubtableRows; if (!statement.validateOnly && parentRows > dmlMaxRows) { throw new Error(`ArgumentError: APPLY parent rows (${parentRows}) exceed dmlMaxRows (${dmlMaxRows}).`); } if (!statement.validateOnly && subtableRows > dmlMaxSubtableRows) { throw new Error( `ArgumentError: APPLY changed subtable rows (${subtableRows}) exceed dmlMaxSubtableRows (${dmlMaxSubtableRows}).` ); } const plans = rawPlans.map( (plan, index) => normalizeApplyPatchPlan(plan, validationResults[index].normalizedRecord) ); const records = plans.flatMap((plan) => applyPatchPlanToKintone(plan).records); const validations = validationResults.map((validation) => ({ errors: validation.errors, columns: validation.columns, invalidRows: validation.invalidRows, errorCount: validation.errorCount })); return deepFreeze({ plans, records, validations, guards: { revisionRequired: true, parentRows, dmlMaxRows, subtableRows, dmlMaxSubtableRows, wouldExceed } }); } function assertPositiveLimit(value, name) { if (!Number.isSafeInteger(value) || value <= 0) { throw new Error(`ArgumentError: ${name} must be a positive safe integer.`); } } function deepFreeze(value, seen = /* @__PURE__ */ new Set()) { if (value === null || typeof value !== "object" || seen.has(value)) return value; seen.add(value); for (const child of Object.values(value)) deepFreeze(child, seen); return Object.freeze(value); } // src/core/applyInsertPrepare.ts init_define_KSQL_DOCS(); var NON_WRITABLE_FIELD_TYPES = /* @__PURE__ */ new Set([ "CALC", "RECORD_NUMBER", "CREATOR", "CREATED_TIME", "MODIFIER", "UPDATED_TIME", "STATUS", "STATUS_ASSIGNEE", "CATEGORY", "REFERENCE_TABLE" ]); function resolveApplyInsertMetadata(statement, fieldInfos) { if (new Set(statement.fields).size !== statement.fields.length) { return argument4("DML target fields contain duplicates."); } const fieldsByCode = new Map(fieldInfos.map((field) => [field.code, field])); for (const code of statement.fields) assertWritable(code, null, fieldsByCode); const targetTables = /* @__PURE__ */ new Map(); const childrenByTable = /* @__PURE__ */ new Map(); for (const block of statement.applyBlocks ?? []) { if (targetTables.has(block.field)) return argument4(`APPLY has more than one block for table ${block.field}.`); const table = fieldInfos.find((field) => field.code === block.field && !field.inSubtable); if (!table || table.fieldType !== "SUBTABLE") return argument4(`APPLY target ${block.field} is not a SUBTABLE.`); const children = new Map(fieldInfos.filter((field) => field.inSubtable && field.subtableCode === block.field).map((field) => [field.code, field])); targetTables.set(block.field, table); childrenByTable.set(block.field, children); for (const operation of block.operations) { if (operation.kind !== "APPEND") return argument4(`APPLY INSERT supports APPEND only (${operation.kind}).`); const specified = /* @__PURE__ */ new Set(); for (const code of operation.fields) { if (specified.has(code)) return argument4(`APPLY APPEND specifies child ${code} more than once.`); specified.add(code); assertWritable(code, block.field, fieldsByCode, children); } for (const row of operation.values) { if (row.length !== operation.fields.length) { return argument4(`APPLY APPEND for ${block.field} has ${row.length} values for ${operation.fields.length} fields.`); } } } } return { targetTables, targetMultiValueFields: /* @__PURE__ */ new Map(), childrenByTable, fieldsByCode }; } function buildApplyInsertCandidates(statement, fieldInfos, metadata = resolveApplyInsertMetadata(statement, fieldInfos), parentRowNumbers) { const fieldTypes = new Map(fieldInfos.map((field) => [field.code, field.fieldType])); const parentRecords = insertToPostBatches(statement, fieldTypes).flatMap((batch) => batch.records); if (parentRowNumbers && parentRowNumbers.length !== parentRecords.length) { throw new Error("InternalError: APPLY create parent row number count differs from VALUES rows."); } const templates = (statement.applyBlocks ?? []).map((block) => { const children = metadata.childrenByTable.get(block.field); const rows = block.operations.flatMap( (operation) => buildApplyAppendRows(operation, children, block.field) ); return { table: block.field, rows, addedRows: rows.length }; }); return parentRecords.map((parentRecord, index) => { const postImage = {}; for (const field of fieldInfos) { if (field.inSubtable || field.fieldType === "SUBTABLE" || field.fieldType === "FILE" || field.writable === false || NON_WRITABLE_FIELD_TYPES.has(field.fieldType)) continue; postImage[field.code] = parentRecord[field.code] ?? { value: appendDefaultValue(field) }; } const record2 = { ...parentRecord }; for (const template of templates) { const rows = template.rows.map((row) => ({ value: row.value })); postImage[template.table] = { value: rows }; record2[template.table] = { value: rows }; } return { parentRowNumber: parentRowNumbers?.[index] ?? index + 1, tables: templates, postImage, record: record2 }; }); } async function prepareApplyInsert(input) { const { statement, fieldInfos, dmlMaxRows, dmlMaxSubtableRows, statementNumber = 1 } = input; assertPositiveLimit2(dmlMaxRows, "dmlMaxRows"); assertPositiveLimit2(dmlMaxSubtableRows, "dmlMaxSubtableRows"); const metadata = input.metadata ?? resolveApplyInsertMetadata(statement, fieldInfos); const rawCandidates = buildApplyInsertCandidates(statement, fieldInfos, metadata, input.parentRowNumbers); const creatableFieldInfos = fieldInfos.filter( (field) => field.fieldType === "SUBTABLE" || field.fieldType !== "FILE" && field.writable !== false && !NON_WRITABLE_FIELD_TYPES.has(field.fieldType) ); const fieldIndex = buildPostImageFieldIndex(creatableFieldInfos, statement.fields); const needsNumberPrecision = rawCandidates.some( (candidate) => postImageNeedsNumberPrecision(candidate.postImage, fieldIndex) ); if (needsNumberPrecision && !input.loadNumberPrecision) { throw new Error("InternalError: APPLY number precision loader is required for NUMBER post-images."); } const numberPrecision = needsNumberPrecision ? await input.loadNumberPrecision() : void 0; const results = rawCandidates.map((candidate) => validatePostImage( candidate.postImage, fieldIndex, numberPrecision, statementNumber, candidate.parentRowNumber, "INSERT" )); if (!statement.validateOnly) { const errors = results.flatMap((result) => result.errors); if (errors.length > 0) { throw new Error(`ArgumentError: APPLY post-image validation failed: ${JSON.stringify({ columns: results[0]?.columns ?? [], errors })}`); } } const parentRows = rawCandidates.length; const subtableRows = rawCandidates.reduce( (sum, candidate) => sum + candidate.tables.reduce((tableSum, table) => tableSum + table.addedRows, 0), 0 ); const wouldExceed = parentRows > dmlMaxRows || subtableRows > dmlMaxSubtableRows; if (!statement.validateOnly && parentRows > dmlMaxRows) { throw new Error(`ArgumentError: APPLY parent rows (${parentRows}) exceed dmlMaxRows (${dmlMaxRows}).`); } if (!statement.validateOnly && subtableRows > dmlMaxSubtableRows) { throw new Error(`ArgumentError: APPLY changed subtable rows (${subtableRows}) exceed dmlMaxSubtableRows (${dmlMaxSubtableRows}).`); } const candidates = rawCandidates.map((candidate, index) => { const normalized = results[index].normalizedRecord; const record2 = {}; for (const code of statement.fields) record2[code] = normalized[code]; for (const table of candidate.tables) { const normalizedRows = normalized[table.table]?.value; record2[table.table] = { value: table.rows.map((sourceRow, rowIndex) => ({ value: Object.fromEntries(Object.keys(sourceRow.value).map((code) => [ code, normalizedRows[rowIndex]?.value?.[code] ?? sourceRow.value[code] ])) })) }; } return { ...candidate, postImage: normalized, record: record2 }; }); const records = candidates.map((candidate) => candidate.record); const batches = []; for (let index = 0; index < records.length; index += 100) { batches.push({ app: statement.appId, records: records.slice(index, index + 100) }); } const validations = results.map((result) => ({ errors: result.errors, columns: result.columns, invalidRows: result.invalidRows, errorCount: result.errorCount })); return deepFreeze2({ applyBlocks: statement.applyBlocks ?? [], candidates, records, batches, validations, guards: { revisionRequired: false, parentRows, dmlMaxRows, subtableRows, dmlMaxSubtableRows, wouldExceed } }); } function assertWritable(code, table, fieldsByCode, children) { if (code.startsWith("_") || code.startsWith("$")) return argument4(`APPLY assignment target ${code} is a system field.`); const field = table === null ? [...fieldsByCode.values()].find((candidate) => candidate.code === code && !candidate.inSubtable) : children?.get(code); if (!field) { const elsewhere = fieldsByCode.get(code); if (table !== null && elsewhere?.inSubtable) return argument4(`APPLY child ${code} does not belong to subtable ${table}.`); return argument4(`APPLY ${table === null ? "parent field" : "child"} ${code} does not exist.`); } if (field.fieldType === "SUBTABLE" || field.fieldType === "FILE" || field.writable === false || NON_WRITABLE_FIELD_TYPES.has(field.fieldType)) { return argument4(`APPLY assignment target ${code} is not writable (${field.fieldType}).`); } } function assertPositiveLimit2(value, name) { if (!Number.isSafeInteger(value) || value <= 0) { throw new Error(`ArgumentError: ${name} must be a positive safe integer.`); } } function argument4(message) { throw new Error(`ArgumentError: ${message}`); } function deepFreeze2(value, seen = /* @__PURE__ */ new Set()) { if (value === null || typeof value !== "object" || seen.has(value)) return value; seen.add(value); for (const child of Object.values(value)) deepFreeze2(child, seen); return Object.freeze(value); } // src/core/applyUpsertPrepare.ts init_define_KSQL_DOCS(); async function prepareApplyUpsert(input) { const { statement, matches, fieldInfos, dmlMaxRows, dmlMaxSubtableRows, statementNumber = 1 } = input; assertPositiveLimit3(dmlMaxRows, "dmlMaxRows"); assertPositiveLimit3(dmlMaxSubtableRows, "dmlMaxSubtableRows"); assertMatchCoverage(statement, matches); const createMatches = matches.filter((match) => match.targetId === void 0); const updateMatches = matches.filter((match) => match.targetId !== void 0); const createStatement = toInsertStatement(statement, createMatches.map((match) => match.sourceRowIndex)); const create = await prepareApplyInsert({ statement: createStatement, fieldInfos, metadata: resolveApplyInsertMetadata(createStatement, fieldInfos), dmlMaxRows, dmlMaxSubtableRows, statementNumber, parentRowNumbers: createMatches.map((match) => match.sourceRowIndex + 1), loadNumberPrecision: input.loadNumberPrecision }); const updateParts = []; const seenTargets = /* @__PURE__ */ new Set(); for (const match of updateMatches) { const targetId = match.targetId; if (seenTargets.has(targetId)) argument5(`UPSERT APPLY resolves more than one source row to parent $id ${targetId}.`); seenTargets.add(targetId); if (!match.snapshot) argument5(`UPSERT APPLY snapshot for parent $id ${targetId} is missing.`); const snapshotId = Number(match.snapshot["$id"]?.value); if (snapshotId !== targetId) argument5(`UPSERT APPLY snapshot $id ${snapshotId} does not match target $id ${targetId}.`); const updateStatement = toUpdateStatement(statement, match.sourceRowIndex, targetId); const metadata = updateStatement.applyBlocks?.length ? resolveApplyPatchMetadata(updateStatement, fieldInfos) : emptyPatchMetadata(fieldInfos); updateParts.push(await prepareApplyPatchWrite({ statement: updateStatement, snapshots: [match.snapshot], fieldInfos, metadata, dmlMaxRows, dmlMaxSubtableRows, statementNumber, parentRowNumbers: [match.sourceRowIndex + 1], loadNumberPrecision: input.loadNumberPrecision })); } const update = combineUpdatePrepared(updateParts, dmlMaxRows, dmlMaxSubtableRows); const parentRows = create.guards.parentRows + update.guards.parentRows; const subtableRows = create.guards.subtableRows + update.guards.subtableRows; const wouldExceed = parentRows > dmlMaxRows || subtableRows > dmlMaxSubtableRows; if (!statement.validateOnly) { const validationErrors = [ ...create.validations.flatMap((validation) => validation.errors), ...update.validations.flatMap((validation) => validation.errors) ]; if (validationErrors.length > 0) { throw new Error(`ArgumentError: APPLY post-image validation failed: ${JSON.stringify({ columns: create.validations[0]?.columns ?? update.validations[0]?.columns ?? [], errors: validationErrors })}`); } } if (!statement.validateOnly && parentRows > dmlMaxRows) { throw new Error(`ArgumentError: APPLY parent rows (${parentRows}) exceed dmlMaxRows (${dmlMaxRows}).`); } if (!statement.validateOnly && subtableRows > dmlMaxSubtableRows) { throw new Error(`ArgumentError: APPLY changed subtable rows (${subtableRows}) exceed dmlMaxSubtableRows (${dmlMaxSubtableRows}).`); } return deepFreeze3({ create, update, createBatches: create.batches, updateBatches: chunk2(update.records, statement.appId), guards: { revisionRequired: update.guards.parentRows > 0, parentRows, dmlMaxRows, subtableRows, dmlMaxSubtableRows, wouldExceed, create: create.guards, update: update.guards } }); } function toInsertStatement(statement, indices) { return { type: "INSERT", appId: statement.appId, fields: [...statement.fields], values: indices.map((index) => statement.values[index]), applyBlocks: statement.onInsertApplyBlocks ?? [], // Branch planners must finish every candidate before mixed errors/guards are raised below. validateOnly: true }; } function toUpdateStatement(statement, sourceRowIndex, targetId) { const assignments = statement.fields.map((field, index) => ({ field, value: statement.values[sourceRowIndex][index] })); return { type: "UPDATE", appId: statement.appId, subtableCode: null, assignments, from: null, where: { type: "BINARY", op: "=", left: { type: "FIELD", tableAlias: null, field: "$id" }, right: { type: "NUMBER", value: targetId, raw: String(targetId) } }, applyBlocks: statement.onUpdateApplyBlocks ?? [], validateOnly: true }; } function emptyPatchMetadata(fieldInfos) { return { targetTables: /* @__PURE__ */ new Map(), targetMultiValueFields: /* @__PURE__ */ new Map(), childrenByTable: /* @__PURE__ */ new Map(), fieldsByCode: new Map(fieldInfos.map((field) => [field.code, field])) }; } function combineUpdatePrepared(parts, dmlMaxRows, dmlMaxSubtableRows) { const plans = parts.flatMap((part) => part.plans); const records = parts.flatMap((part) => part.records); const validations = parts.flatMap((part) => part.validations); const subtableRows = plans.reduce((sum, plan) => sum + plan.changedSubtableRows, 0); return deepFreeze3({ plans, records, validations, guards: { revisionRequired: true, parentRows: plans.length, dmlMaxRows, subtableRows, dmlMaxSubtableRows, wouldExceed: plans.length > dmlMaxRows || subtableRows > dmlMaxSubtableRows } }); } function assertMatchCoverage(statement, matches) { if (matches.length !== statement.values.length) { throw new Error("InternalError: UPSERT APPLY match count differs from VALUES rows."); } const seen = /* @__PURE__ */ new Set(); for (const match of matches) { if (!Number.isSafeInteger(match.sourceRowIndex) || match.sourceRowIndex < 0 || match.sourceRowIndex >= statement.values.length || seen.has(match.sourceRowIndex)) { throw new Error("InternalError: UPSERT APPLY matches must cover each source row exactly once."); } seen.add(match.sourceRowIndex); } } function chunk2(records, app) { const batches = []; for (let index = 0; index < records.length; index += 100) { batches.push({ app, records: records.slice(index, index + 100) }); } return batches; } function assertPositiveLimit3(value, name) { if (!Number.isSafeInteger(value) || value <= 0) { throw new Error(`ArgumentError: ${name} must be a positive safe integer.`); } } function argument5(message) { throw new Error(`ArgumentError: ${message}`); } function deepFreeze3(value, seen = /* @__PURE__ */ new Set()) { if (value === null || typeof value !== "object" || seen.has(value)) return value; seen.add(value); for (const child of Object.values(value)) deepFreeze3(child, seen); return Object.freeze(value); } // src/core/applyInsertExecutePrepared.ts init_define_KSQL_DOCS(); // src/core/applyPatchExecutePrepared.ts init_define_KSQL_DOCS(); // src/core/applyDiagnostic.ts init_define_KSQL_DOCS(); function buildPreparedApplyUpdateDiagnostic(prepared) { return diagnostic("UPDATE", [buildPreparedUpdateBranch(prepared)]); } function buildPreparedApplyInsertDiagnostic(prepared) { return diagnostic("INSERT", [buildPreparedInsertBranch(prepared)]); } function buildPreparedApplyUpsertDiagnostic(prepared) { return diagnostic("UPSERT", [ buildPreparedInsertBranch(prepared.create), buildPreparedUpdateBranch(prepared.update) ]); } function withApplyDiagnosticProgress(base, progress) { const failedBranch = progress.failedBranch?.toLowerCase(); const branches = base.branches.map((branch) => { const successfulParents = base.statementKind === "UPSERT" ? branch.branch === "insert" ? progress.successfulInserts : progress.successfulUpdates : progress.successfulParents; const successfulChunks = base.statementKind === "UPSERT" ? branch.branch === "insert" ? progress.successfulInsertChunks : progress.successfulUpdateChunks : progress.successfulChunks; const isFailedBranch = failedBranch === branch.branch; return { ...branch, ...successfulParents !== void 0 ? { successfulParents } : {}, chunk: { ...branch.chunk, ...successfulChunks !== void 0 ? { successfulChunks } : {}, ...isFailedBranch && progress.failedChunkIndex !== void 0 ? { failedChunkIndex: progress.failedChunkIndex } : {}, ...isFailedBranch && progress.failedStage !== void 0 ? { failedStage: progress.failedStage } : {} } }; }); return { ...base, branches, partialSuccess: { possible: true, successfulParents: progress.successfulParents, successfulChunks: progress.successfulChunks, ...failedBranch ? { failedBranch } : {}, ...progress.retryAttempted !== void 0 ? { retryAttempted: progress.retryAttempted } : {} } }; } function buildStaticApplyDiagnostic(statement, dmlMaxRows, dmlMaxSubtableRows) { if (statement.type === "UPDATE") { return diagnostic("UPDATE", [staticBranch( "update", statement.applyBlocks ?? [], null, true, dmlMaxRows, dmlMaxSubtableRows )]); } if (statement.type === "INSERT") { return diagnostic("INSERT", [staticBranch( "insert", statement.applyBlocks ?? [], statement.values.length, false, dmlMaxRows, dmlMaxSubtableRows )]); } return diagnostic("UPSERT", [ staticBranch("insert", statement.onInsertApplyBlocks ?? [], null, false, dmlMaxRows, dmlMaxSubtableRows), staticBranch("update", statement.onUpdateApplyBlocks ?? [], null, true, dmlMaxRows, dmlMaxSubtableRows) ]); } function diagnostic(statementKind, branches) { return { statementKind, branches, nonTransactional: true, partialSuccess: { possible: true } }; } function buildPreparedInsertBranch(prepared) { const targets = /* @__PURE__ */ new Map(); if (prepared.applyBlocks) { for (const block of prepared.applyBlocks) { const operations = block.operations.map((operation) => { if (operation.kind !== "APPEND") { throw new Error(`InternalError: prepared APPLY INSERT contains ${operation.kind}.`); } const addedRows = operation.values.length * prepared.guards.parentRows; return { kind: "APPEND", count: addedRows, addedRows }; }); targets.set(block.field, { targetKind: block.targetKind, field: block.field, operations, changedCount: operations.reduce((sum, operation) => sum + (operation.addedRows ?? 0), 0) }); } } else { for (const candidate of prepared.candidates) { for (const table of candidate.tables) { const current = targets.get(table.table); const addedRows = current?.operations[0]?.addedRows ?? 0; targets.set(table.table, { targetKind: "SUBTABLE", field: table.table, operations: [{ kind: "APPEND", count: addedRows + table.addedRows, addedRows: addedRows + table.addedRows }], changedCount: (current?.changedCount ?? 0) + table.addedRows }); } } } return { branch: "insert", parentRows: prepared.guards.parentRows, targets: [...targets.values()], guards: prepared.guards, chunk: { size: 100, plannedChunks: prepared.batches.length }, deletedParentRows: 0 }; } function buildPreparedUpdateBranch(prepared) { const targets = /* @__PURE__ */ new Map(); let deletedParentRows = 0; for (const plan of prepared.plans) { let parentHasDeletes = false; for (const table of plan.tables) { const current = targets.get(table.table); targets.set(table.table, { targetKind: "SUBTABLE", field: table.table, operations: mergeOperations(current?.operations, table.operations.map((operation) => ({ ...operation, count: operation.kind === "PATCH" ? operation.changedRows : operation.kind === "APPEND" ? operation.addedRows : operation.removedRows }))), changedCount: (current?.changedCount ?? 0) + table.changedSubtableRows }); parentHasDeletes ||= table.deletedRows > 0; } for (const field of plan.multiValues) { const current = targets.get(field.field); const postImage = { parentId: plan.parentId, value: field.postImageValue }; targets.set(field.field, { targetKind: "MULTI_VALUE", field: field.field, fieldType: field.fieldType, operations: mergeOperations(current?.operations, field.operations.map((operation) => ({ kind: operation.kind, value: operation.value, count: operation.changed ? 1 : 0, changed: operation.changed }))), changedCount: (current?.changedCount ?? 0) + field.changedValues, postImages: [...current?.postImages ?? [], postImage] }); } if (parentHasDeletes) deletedParentRows += 1; } return { branch: "update", parentRows: prepared.guards.parentRows, targets: [...targets.values()], guards: prepared.guards, chunk: { size: 100, plannedChunks: Math.ceil(prepared.records.length / 100) }, deletedParentRows }; } function mergeOperations(current, next) { if (!current) return next.map((operation) => ({ ...operation })); return next.map((operation, index) => { const previous = current[index]; if (!previous || previous.kind !== operation.kind || previous.value !== operation.value) { throw new Error("InternalError: APPLY diagnostic operation shape differs between parents."); } return { ...operation, ...previous.changed !== void 0 ? { changed: previous.changed } : {}, count: addNullable(previous.count, operation.count), ...operation.matchedRows !== void 0 ? { matchedRows: addNullable(previous.matchedRows, operation.matchedRows) } : {}, ...operation.changedRows !== void 0 ? { changedRows: addNullable(previous.changedRows, operation.changedRows) } : {}, ...operation.addedRows !== void 0 ? { addedRows: addNullable(previous.addedRows, operation.addedRows) } : {}, ...operation.removedRows !== void 0 ? { removedRows: addNullable(previous.removedRows, operation.removedRows) } : {} }; }); } function addNullable(left, right) { return left === null || left === void 0 || right === null ? null : left + right; } function staticBranch(branch, blocks, parentRows, revisionRequired, dmlMaxRows, dmlMaxSubtableRows) { const targets = blocks.map((block) => { const operations = block.operations.map((operation) => staticOperation(operation, parentRows)); const changedCount = operations.every((operation) => operation.count !== null) ? operations.reduce((sum, operation) => sum + operation.count, 0) : null; return { targetKind: block.targetKind, field: block.field, operations, changedCount }; }); const subtableTargets = targets.filter((target) => target.targetKind === "SUBTABLE"); const subtableRows = subtableTargets.every((target) => target.changedCount !== null) ? subtableTargets.reduce((sum, target) => sum + target.changedCount, 0) : null; const wouldExceed = parentRows === null || subtableRows === null ? null : parentRows > dmlMaxRows || subtableRows > dmlMaxSubtableRows; return { branch, parentRows, targets, guards: { revisionRequired, parentRows, dmlMaxRows, subtableRows, dmlMaxSubtableRows, wouldExceed }, chunk: { size: 100, plannedChunks: parentRows === null ? null : Math.ceil(parentRows / 100) }, deletedParentRows: branch === "insert" ? 0 : null }; } function staticOperation(operation, parentRows) { if (operation.kind === "APPEND") { const addedRows = parentRows === null ? null : operation.values.length * parentRows; return { kind: operation.kind, count: addedRows, addedRows }; } if (operation.kind === "PATCH") return { kind: operation.kind, count: null, matchedRows: null, changedRows: null }; if (operation.kind === "REMOVE") return { kind: operation.kind, count: null, removedRows: null }; return { kind: operation.kind, value: operation.value, count: null }; } // src/core/applyPatchExecutePrepared.ts var ApplyWritePartialFailureError = class extends Error { constructor(partialSuccess, cause) { const detail = cause instanceof Error ? cause.message : String(cause); const method = partialSuccess.failedStage === "POST_CHUNK" ? "POST" : "PUT"; const branch = partialSuccess.failedBranch ? ` UPSERT ${partialSuccess.failedBranch}` : ""; super( `ApplyWritePartialFailureError: APPLY${branch} ${method} chunk ${partialSuccess.failedChunkIndex + 1} failed (index ${partialSuccess.failedChunkIndex}) after ${partialSuccess.successfulChunks} successful chunk(s) and ${partialSuccess.successfulParents} successful parent(s); writes are non-transactional and were not retried. Cause: ${detail}` ); this.name = "ApplyWritePartialFailureError"; this.partialSuccess = partialSuccess; this.cause = cause; } }; async function executePreparedApplyWrite(prepared, client, diagnostic2) { assertApplyInternalWriteScope("phase10c"); const batches = applyPatchPlansToKintoneBatches(prepared); let successfulChunks = 0; let successfulParents = 0; for (let failedChunkIndex = 0; failedChunkIndex < batches.length; failedChunkIndex += 1) { const batch = batches[failedChunkIndex]; try { await client.putRecords(batch); } catch (cause) { throw new ApplyWritePartialFailureError({ successfulChunks, successfulParents, failedChunkIndex, failedStage: "PUT_CHUNK", nonTransactional: true, retryAttempted: false, ...diagnostic2 ? { diagnostic: withApplyDiagnosticProgress(diagnostic2, { successfulChunks, successfulParents, failedChunkIndex, failedStage: "PUT_CHUNK", failedBranch: "UPDATE", retryAttempted: false }) } : {} }, cause); } successfulChunks += 1; successfulParents += batch.records.length; } return { type: "UPDATE", updatedCount: successfulParents, successfulChunks, successfulParents, nonTransactional: true }; } // src/core/applyInsertExecutePrepared.ts async function executePreparedApplyInsert(prepared, client, diagnostic2) { assertApplyInternalWriteScope("phase13c"); const createdIds = []; let successfulChunks = 0; let successfulParents = 0; for (let failedChunkIndex = 0; failedChunkIndex < prepared.batches.length; failedChunkIndex += 1) { const batch = prepared.batches[failedChunkIndex]; try { const response = await client.postRecords({ app: batch.app, records: [...batch.records] }); createdIds.push(response.ids); } catch (cause) { throw new ApplyWritePartialFailureError({ successfulChunks, successfulParents, failedChunkIndex, failedStage: "POST_CHUNK", nonTransactional: true, retryAttempted: false, ...diagnostic2 ? { diagnostic: withApplyDiagnosticProgress(diagnostic2, { successfulChunks, successfulParents, failedChunkIndex, failedStage: "POST_CHUNK", failedBranch: "INSERT", retryAttempted: false }) } : {} }, cause); } successfulChunks += 1; successfulParents += batch.records.length; } return { type: "INSERT", createdIds, insertedCount: successfulParents, successfulChunks, successfulParents, nonTransactional: true }; } // src/core/applyUpsertExecutePrepared.ts init_define_KSQL_DOCS(); async function executePreparedApplyUpsert(prepared, client, diagnostic2) { assertApplyInternalWriteScope("phase14c"); const createdIds = []; let successfulInsertChunks = 0; let successfulUpdateChunks = 0; let successfulInserts = 0; let successfulUpdates = 0; for (let failedChunkIndex = 0; failedChunkIndex < prepared.createBatches.length; failedChunkIndex += 1) { const batch = prepared.createBatches[failedChunkIndex]; try { const response = await client.postRecords({ app: batch.app, records: [...batch.records] }); createdIds.push(response.ids); } catch (cause) { throw new ApplyWritePartialFailureError({ successfulChunks: successfulInsertChunks + successfulUpdateChunks, successfulParents: successfulInserts + successfulUpdates, successfulInserts, successfulUpdates, failedChunkIndex, failedBranch: "INSERT", failedStage: "POST_CHUNK", nonTransactional: true, retryAttempted: false, ...diagnostic2 ? { diagnostic: withApplyDiagnosticProgress(diagnostic2, { successfulChunks: successfulInsertChunks + successfulUpdateChunks, successfulParents: successfulInserts + successfulUpdates, successfulInserts, successfulUpdates, successfulInsertChunks, successfulUpdateChunks, failedChunkIndex, failedStage: "POST_CHUNK", failedBranch: "INSERT", retryAttempted: false }) } : {} }, cause); } successfulInsertChunks += 1; successfulInserts += batch.records.length; } for (let failedChunkIndex = 0; failedChunkIndex < prepared.updateBatches.length; failedChunkIndex += 1) { const batch = prepared.updateBatches[failedChunkIndex]; try { await client.putRecords({ app: batch.app, records: [...batch.records] }); } catch (cause) { throw new ApplyWritePartialFailureError({ successfulChunks: successfulInsertChunks + successfulUpdateChunks, successfulParents: successfulInserts + successfulUpdates, successfulInserts, successfulUpdates, failedChunkIndex, failedBranch: "UPDATE", failedStage: "PUT_CHUNK", nonTransactional: true, retryAttempted: false, ...diagnostic2 ? { diagnostic: withApplyDiagnosticProgress(diagnostic2, { successfulChunks: successfulInsertChunks + successfulUpdateChunks, successfulParents: successfulInserts + successfulUpdates, successfulInserts, successfulUpdates, successfulInsertChunks, successfulUpdateChunks, failedChunkIndex, failedStage: "PUT_CHUNK", failedBranch: "UPDATE", retryAttempted: false }) } : {} }, cause); } successfulUpdateChunks += 1; successfulUpdates += batch.records.length; } return { type: "UPSERT", createdIds, insertedCount: successfulInserts, updatedCount: successfulUpdates, successfulChunks: successfulInsertChunks + successfulUpdateChunks, successfulParents: successfulInserts + successfulUpdates, successfulInsertChunks, successfulUpdateChunks, nonTransactional: true }; } // src/core/batchVariables.ts init_define_KSQL_DOCS(); var VARIABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/; function normalizeBatchVariableName(name) { if (!VARIABLE_NAME_RE.test(name)) { throw new Error( `ArgumentError: invalid variable name "${name}". Use a name without @ matching [A-Za-z_][A-Za-z0-9_]{0,63}.` ); } return name.toLowerCase(); } function normalizeBatchVariables(input) { const normalized = /* @__PURE__ */ Object.create(null); for (const [rawName, value] of Object.entries(input ?? {})) { const name = normalizeBatchVariableName(rawName); if (Object.prototype.hasOwnProperty.call(normalized, name)) { throw new Error(`ArgumentError: variable "${rawName}" is specified more than once.`); } normalized[name] = value; } return normalized; } function validateDeclaredBatchVariables(statements, input) { const normalized = normalizeBatchVariables(input); const declared = new Set( statements.filter((stmt) => stmt.type === "DECLARE_VARIABLE").map((stmt) => stmt.name) ); for (const name of Object.keys(normalized)) { if (!declared.has(name)) { throw new Error(`ArgumentError: injected variable @${name} is not declared.`); } } return normalized; } // src/core/explainMetadata.ts init_define_KSQL_DOCS(); function whereNeedsFieldMetadata(where) { if (where === null) return false; switch (where.type) { case "BINARY": return valueNeedsFieldMetadata(where.left); case "NULL_CHECK": return valueNeedsFieldMetadata(where.field); case "LOGICAL": return whereNeedsFieldMetadata(where.left) || whereNeedsFieldMetadata(where.right); case "NOT": case "GROUP": return whereNeedsFieldMetadata(where.expr); case "EXISTS": case "BOOLEAN": return false; } } function valueNeedsFieldMetadata(value) { if (Array.isArray(value)) return value.some(valueNeedsFieldMetadata); if (value === null || typeof value !== "object") return false; const item = value; if (item["type"] === "FIELD") return item["field"] !== "$id"; if (item["type"] === "SELECT") return false; return Object.values(item).some(valueNeedsFieldMetadata); } function selectNeedsOwnMetadata(statement) { return whereNeedsFieldMetadata(statement.where) || statement.orderBy.length > 0 || statement.columns.some( (column) => column.type === "WINDOW_COL" && column.orderBy.length > 0 ); } function explainNeedsAppMetadata(statement) { const seen = /* @__PURE__ */ new Set(); const visit = (node) => { if (node === null || typeof node !== "object") return false; if (seen.has(node)) return false; seen.add(node); if (Array.isArray(node)) return node.some(visit); const item = node; if (item["type"] === "VALIDATE") return true; if (item["type"] === "SELECT" && selectNeedsOwnMetadata(node)) { return true; } if ((item["type"] === "UPDATE" || item["type"] === "DELETE") && whereNeedsFieldMetadata(node.where)) { return true; } if (item["type"] === "UPDATE" && Array.isArray(item["applyBlocks"]) && item["applyBlocks"].length > 0) return true; return Object.values(item).some(visit); }; return visit(statement); } // src/api/fetchAll.ts init_define_KSQL_DOCS(); async function fetchAll(fetcher, app, query, fields, options = {}) { const pageSize = options.pageSize ?? PAGE_SIZE_DEFAULT; const parallel = Math.max(1, options.parallel ?? PARALLEL_DEFAULT); const maxRecords2 = options.maxRecords ?? MAX_RECORDS_DEFAULT; const onLimit2 = options.onLimit ?? "error"; const stopAfter = options.stopAfter; if (stopAfter !== void 0 && (!Number.isSafeInteger(stopAfter) || stopAfter <= 0 || stopAfter > maxRecords2)) { throw new RangeError("stopAfter must be a positive safe integer <= maxRecords"); } const fetchCap = stopAfter ?? maxRecords2; const fetchFields = fields.length > 0 && !fields.includes("$id") ? [...fields, "$id"] : fields; const allRecords = []; let notified = false; const limitMessage = `\u53D6\u5F97\u4EF6\u6570\u304C\u4E0A\u9650\uFF08${maxRecords2} \u4EF6\uFF09\u3092\u8D85\u3048\u307E\u3057\u305F\u3002WHERE \u53E5\u3067\u7D5E\u308A\u8FBC\u3080\u304B\u3001maxRecords \u3092\u5F15\u304D\u4E0A\u3052\u3066\u304F\u3060\u3055\u3044\u3002`; let cursorId = 0; let windowOffset = 0; const cursorQuery0 = buildCursorQuery(query, cursorId); const first = await fetchPage(fetcher, app, cursorQuery0, fetchFields, pageSize, windowOffset); notifySearchAborted(first, options); allRecords.push(...first.records); if (stopAfter !== void 0 && allRecords.length >= stopAfter) { return allRecords.slice(0, stopAfter); } if (allRecords.length > maxRecords2) { if (onLimit2 === "truncate") { if (!notified && options.onTruncate) { options.onTruncate(maxRecords2); notified = true; } return allRecords.slice(0, maxRecords2); } throw new FetchAllLimitError(limitMessage); } if (first.records.length < pageSize) return allRecords; windowOffset += pageSize; if (windowOffset >= KINTONE_MAX_OFFSET) { cursorId = getLastId(first.records); windowOffset = 0; } while (true) { if (stopAfter !== void 0 && allRecords.length >= stopAfter) { return allRecords.slice(0, stopAfter); } if (allRecords.length >= maxRecords2) { if (onLimit2 === "truncate") { if (!notified && options.onTruncate) { options.onTruncate(maxRecords2); notified = true; } return allRecords.slice(0, maxRecords2); } throw new FetchAllLimitError(limitMessage); } const remaining = fetchCap - allRecords.length; const maxPagesByLimit = Math.ceil(remaining / pageSize); const batchParallel = Math.max(1, Math.min(parallel, maxPagesByLimit)); const batchOffsets = []; for (let i = 0; i < batchParallel; i++) { const off = windowOffset + i * pageSize; if (off >= KINTONE_MAX_OFFSET) break; batchOffsets.push(off); } const cq = buildCursorQuery(query, cursorId); const responses = await Promise.all( batchOffsets.map( (offset) => fetchPage(fetcher, app, cq, fetchFields, pageSize, offset) ) ); for (const response of responses) notifySearchAborted(response, options); let done = false; for (const res of responses) { allRecords.push(...res.records); if (stopAfter !== void 0 && allRecords.length >= stopAfter) { return allRecords.slice(0, stopAfter); } if (allRecords.length > maxRecords2) { if (onLimit2 === "truncate") { if (!notified && options.onTruncate) { options.onTruncate(maxRecords2); notified = true; } return allRecords.slice(0, maxRecords2); } throw new FetchAllLimitError(limitMessage); } if (res.records.length < pageSize) { done = true; break; } } if (done) break; windowOffset += pageSize * batchOffsets.length; if (windowOffset >= KINTONE_MAX_OFFSET) { const lastRes = responses[responses.length - 1]; cursorId = getLastId(lastRes.records); windowOffset = 0; } } return allRecords; } function notifySearchAborted(response, options) { if (response.searchAborted) options.onSearchAborted?.(); } function extractIds(records) { return records.map((r) => { const raw = r["$id"]?.value; if (raw === void 0) { throw new Error( '\u30EC\u30B3\u30FC\u30C9\u306B $id \u30D5\u30A3\u30FC\u30EB\u30C9\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002fields \u306B "$id" \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002' ); } const id = Number(raw); if (!Number.isFinite(id)) { throw new Error(`$id \u306E\u5024\u304C\u6570\u5024\u3067\u306F\u3042\u308A\u307E\u305B\u3093: ${raw}`); } return id; }); } var PAGE_SIZE_DEFAULT = 500; var PARALLEL_DEFAULT = 1; var MAX_RECORDS_DEFAULT = 1e4; var KINTONE_MAX_OFFSET = 1e4; async function fetchPage(fetcher, app, query, fields, pageSize, offset) { const pageQuery = buildPageQuery(query, pageSize, offset); return fetcher({ app, query: pageQuery, fields }); } function buildCursorQuery(baseQuery, cursorId) { const base = baseQuery.trimEnd(); if (cursorId <= 0) { return base ? `${base} order by $id asc` : "order by $id asc"; } const cursor = `$id > ${cursorId} order by $id asc`; return base ? `(${base}) and ${cursor}` : cursor; } function buildPageQuery(query, pageSize, offset) { const base = query.trimEnd(); const suffix = `limit ${pageSize} offset ${offset}`; return base ? `${base} ${suffix}` : suffix; } function getLastId(records) { const last = records[records.length - 1]; const raw = last?.["$id"]?.value; if (raw === void 0) return 0; const id = Number(raw); return Number.isFinite(id) ? id : 0; } var FetchAllLimitError = class extends Error { constructor(message) { super(message); this.name = "FetchAllLimitError"; } }; // src/core/optimization/sharedPlanner.ts init_define_KSQL_DOCS(); async function fetchRecordsForSharedPlan(getRecords, app, query, fields, options) { const records = await fetchAll(getRecords, app, query, fields, { maxRecords: options.maxRecords, parallel: options.parallel, onLimit: options.onLimit ?? "error", onTruncate: options.onTruncate, onSearchAborted: options.onSearchAborted }); return { records, metrics: { fetchedRows: records.length } }; } async function resolveDmlTargetIds(getRecords, app, query, options) { const { records, metrics } = await fetchRecordsForSharedPlan( getRecords, app, query, ["$id"], options ); return { ids: extractIds(records), metrics }; } // src/core/optimization/applyParentSelectionPlan.ts init_define_KSQL_DOCS(); function buildApplyParentSelectionPlan(where, metadata) { const plan = buildSingleTableKlikePushdownPlan(where, { allowUnqualifiedFields: true, allowKlike: true, fieldTypes: metadata.fieldTypes, fieldOptions: metadata.fieldOptions }); return { prefilter: plan.condition, appliedKlikes: plan.appliedKlikes, unappliedKlikes: plan.allKlikes.filter((expr) => !plan.appliedKlikes.has(expr)) }; } // src/core/optimization/canonicalOrderPlanner.ts init_define_KSQL_DOCS(); var REST_OFFSET_MAX = 1e4; var REST_LIMIT_MAX = 500; function fieldSemantics(item, semantics) { return item.key.type === "FIELD_NAME" ? semantics.get(item.key.name) : void 0; } function hasSelectOutputAlias(stmt, name) { return stmt.columns.some((column) => "alias" in column && column.alias === name); } function planCanonicalOrder(input) { const { stmt } = input; const reasons = []; const windowOrderBy = stmt.columns.flatMap( (column) => column.type === "WINDOW_COL" ? column.orderBy : [] ); const allOrderBy = [...stmt.orderBy, ...windowOrderBy]; for (const item of allOrderBy) { if (item.key.type !== "FIELD_NAME") continue; const semantics = fieldSemantics(item, input.orderSemantics); if (!semantics) { reasons.push("ORDER_KEY_UNRESOLVED"); continue; } if (semantics.fieldType === "KSQL_AMBIGUOUS") reasons.push("ORDER_KEY_AMBIGUOUS"); else if (semantics.compareMode === "unsupported") reasons.push("ORDER_KEY_UNSUPPORTED"); } if (reasons.includes("ORDER_KEY_AMBIGUOUS")) { throw new Error( "ArgumentError: ORDER BY key is an ambiguous column reference (reason=ORDER_KEY_AMBIGUOUS). Qualify the key with its table alias." ); } if (reasons.includes("ORDER_KEY_UNSUPPORTED") || reasons.includes("ORDER_KEY_UNRESOLVED")) { const reason = reasons.includes("ORDER_KEY_UNSUPPORTED") ? "ORDER_KEY_UNSUPPORTED" : "ORDER_KEY_UNRESOLVED"; throw new Error(`ArgumentError: ORDER BY key has no canonical comparison contract (reason=${reason}).`); } const allRestEquivalent = stmt.orderBy.length > 0 && windowOrderBy.length === 0 && stmt.orderBy.every( (item) => item.key.type === "FIELD_NAME" && item.key.name === "$id" && !hasSelectOutputAlias(stmt, item.key.name) ); if (!allRestEquivalent) reasons.push("ORDER_KEY_NOT_REST_EQUIVALENT"); if (input.whereCapability !== "EXACT_PUSHDOWN") reasons.push("WHERE_NOT_EXACT"); if (input.staticMode !== "SIMPLE") reasons.push("QUERY_SHAPE_LOCAL"); if (stmt.limit === null || stmt.limit < 0 || stmt.limit > REST_LIMIT_MAX) { reasons.push("LIMIT_NOT_REST_WINDOW"); } if ((stmt.offset ?? 0) < 0 || (stmt.offset ?? 0) > REST_OFFSET_MAX) { reasons.push("OFFSET_NOT_REST_WINDOW"); } if (stmt.limit !== null && stmt.limit > input.maxRecords) reasons.push("MAX_RECORDS_WINDOW"); if (input.hasKlike) reasons.push("KLIKE_NOT_REST_WINDOW"); if (reasons.length === 0) { return { kind: "CANONICAL_REST_TOP_N", requiresCompleteInput: false, localOrderBy: false, applyLocalOffsetLimit: false, reasonCodes: [] }; } return { kind: "CANONICAL_LOCAL", requiresCompleteInput: allOrderBy.length > 0, localOrderBy: stmt.orderBy.length > 0, applyLocalOffsetLimit: stmt.orderBy.length > 0, reasonCodes: [...new Set(reasons)] }; } // src/core/optimization/korderPlanner.ts init_define_KSQL_DOCS(); var KORDER_NATIVE_FIELD_TYPES = /* @__PURE__ */ new Set([ "RECORD_NUMBER", "SINGLE_LINE_TEXT", "NUMBER", "CALC", "DATE", "DATETIME", "TIME", "CREATED_TIME", "UPDATED_TIME", "DROP_DOWN", "RADIO_BUTTON", "STATUS", "LINK", "CREATOR", "MODIFIER" ]); function hasSelectOutputAlias2(stmt, name) { return stmt.columns.some((column) => "alias" in column && column.alias === name); } function planKorder(input) { const { stmt } = input; const reasons = []; if (stmt.orderMode !== "KINTONE_NATIVE") reasons.push("KORDER_MODE_REQUIRED"); if (stmt.from.cteName !== null || stmt.from.subtableCode || input.staticMode !== "SIMPLE") { reasons.push("KORDER_QUERY_SHAPE_UNSUPPORTED"); } if (input.whereCapability !== "EXACT_PUSHDOWN") reasons.push("KORDER_WHERE_NOT_EXACT"); if (input.hasKlike) reasons.push("KORDER_KLIKE_UNSUPPORTED"); if (stmt.orderBy.length === 0) reasons.push("KORDER_KEY_REQUIRED"); for (const item of stmt.orderBy) { if (item.key.type !== "FIELD_NAME") { reasons.push(`KORDER_KEY_NOT_DIRECT_FIELD(key=${item.key.type})`); continue; } const name = item.key.name; const semantics = input.orderSemantics.get(name); if (!semantics) { reasons.push(`KORDER_KEY_UNRESOLVED(field=${name})`); continue; } if (hasSelectOutputAlias2(stmt, name)) { reasons.push(`KORDER_KEY_NOT_DIRECT_FIELD(field=${name})`); continue; } if (name === "$id") continue; if (!semantics.source || semantics.source.fieldCode !== name) { reasons.push(`KORDER_KEY_NOT_DIRECT_FIELD(field=${name})`); continue; } if (!KORDER_NATIVE_FIELD_TYPES.has(semantics.fieldType)) { reasons.push(`KORDER_TYPE_UNSUPPORTED(field=${name}, type=${semantics.fieldType})`); } } if (stmt.limit === null || !Number.isSafeInteger(stmt.limit) || stmt.limit < 0) { reasons.push(`KORDER_LIMIT_INVALID(limit=${String(stmt.limit)})`); } const offset = stmt.offset ?? 0; if (!Number.isSafeInteger(offset) || offset < 0) { reasons.push(`KORDER_OFFSET_INVALID(offset=${offset})`); } const scanRows = stmt.limit === null ? Number.NaN : offset + stmt.limit; if (stmt.limit !== null && !Number.isSafeInteger(scanRows)) { reasons.push(`KORDER_SCAN_ROWS_INVALID(offset=${offset}, limit=${stmt.limit})`); } const unique = [...new Set(reasons)]; if (unique.length > 0) { throw new Error( `ArgumentError: KORDER BY cannot be executed (mode=KINTONE_NATIVE; ${unique.join(", ")}). Use ORDER BY for canonical local ordering or simplify the query.` ); } const native = stmt.limit <= 500 && offset <= 1e4 && stmt.limit <= input.maxRecords; if (!native && scanRows > input.maxRecords) { throw new Error( `ArgumentError: KORDER BY cannot be executed (mode=KINTONE_NATIVE; KORDER_SCAN_ROWS_EXCEEDS_MAX_RECORDS(scanRows=${scanRows}, maxRecords=${input.maxRecords})). Use ORDER BY for canonical local ordering, raise maxRecords, or reduce LIMIT/OFFSET.` ); } return { kind: native ? "KORDER_NATIVE" : "KORDER_CURSOR", requiresCompleteInput: false, localOrderBy: false, applyLocalOffsetLimit: false, reasonCodes: [], scanRows }; } // src/core/optimization/korderCursorExecutor.ts init_define_KSQL_DOCS(); // src/core/errors/cursorErrors.ts init_define_KSQL_DOCS(); var CursorCapacityError = class extends Error { constructor(host, limit, waitMs) { super(`CursorCapacityError: host=${host} \u306E active cursor \u4E0A\u9650 ${limit} \u306B ${waitMs}ms \u4EE5\u5185\u3067\u7A7A\u304D\u304C\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002`); this.name = "CursorCapacityError"; } }; var CursorCreateOutcomeUnknownError = class extends Error { constructor(cause) { super("CursorCreateOutcomeUnknownError: Create Cursor \u306E\u6210\u5426\u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093\u3002\u81EA\u52D5\u518D\u8A66\u884C\u305B\u305A\u3001\u6700\u592710\u5206+\u5B89\u5168\u4F59\u88D5\u306E\u9593\u306F\u67A0\u3092\u9694\u96E2\u3057\u307E\u3059\u3002"); this.name = "CursorCreateOutcomeUnknownError"; this.cause = cause; } }; var CursorCleanupWarning = class extends Error { constructor(cause) { const detail = cause instanceof Error ? cause.message : String(cause); super(`CursorCleanupWarning: Cursor \u306E\u89E3\u653E\u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093\u3002\u7D50\u679C\u306F\u6709\u52B9\u3067\u3059\u304C\u3001\u6700\u592710\u5206+\u5B89\u5168\u4F59\u88D5\u306E\u9593\u306F\u67A0\u3092\u9694\u96E2\u3057\u307E\u3059\u3002\u8A73\u7D30: ${detail}`); this.name = "CursorCleanupWarning"; this.cause = cause; } }; // src/core/optimization/korderCursorExecutor.ts async function executeKorderCursor(input) { const handle = await input.client.openCursor({ app: input.app, fields: input.fields.length > 0 ? input.fields : void 0, query: input.query, size: 500 }); const records = []; let seen = 0; let primaryError; let cleanupWarning; try { if (handle.totalCount > input.offset) { while (records.length < input.limit) { const page = await handle.nextPage(); for (const record2 of page.records) { if (seen < input.offset) seen += 1; else if (records.length < input.limit) records.push(record2); else break; } if (!page.next) break; } } } catch (error51) { primaryError = error51; throw error51; } finally { try { await handle.close(); } catch (cleanupError) { if (primaryError && primaryError instanceof Error) { Object.defineProperty(primaryError, "cursorCleanupError", { value: cleanupError, configurable: true }); } else { cleanupWarning = new CursorCleanupWarning(cleanupError).message; } } } return { records, cleanupWarning }; } // src/converter/korderCursorQuery.ts init_define_KSQL_DOCS(); function buildKorderCursorQuery(stmt) { const parts = []; if (stmt.where) parts.push(whereToKintone(stmt.where)); const order = stmt.orderBy.map((item) => { if (item.key.type !== "FIELD_NAME") { throw new Error("ArgumentError: KORDER cursor key must be a direct field."); } return `${item.key.name} ${item.direction === "ASC" ? "asc" : "desc"}`; }); parts.push(`order by ${order.join(", ")}`); return parts.join(" "); } // src/engine/process.ts init_define_KSQL_DOCS(); function flatten(record2, alias) { const row = {}; for (const [field, fv] of Object.entries(record2)) { const val = fv.value; const strVal = val == null ? "" : typeof val === "string" ? val : JSON.stringify(val); if (alias) { row[`${alias}.${field}`] = strVal; row[field] = strVal; } else { row[field] = strVal; } } return row; } function applyJoin(leftRows, rightRows, join, columns = {}) { const { on, type: joinType } = join; const leftKey = on.left.tableAlias ? `${on.left.tableAlias}.${on.left.field}` : on.left.field; const rightKey = on.right.tableAlias ? `${on.right.tableAlias}.${on.right.field}` : on.right.field; assertJoinKeyAvailable(leftRows, leftKey, columns.leftColumns); assertJoinKeyAvailable(rightRows, rightKey, columns.rightColumns); if (joinType === "RIGHT") { const leftIndex = /* @__PURE__ */ new Map(); for (const lRow of leftRows) { const k = lRow[leftKey] ?? ""; const bucket = leftIndex.get(k); if (bucket) bucket.push(lRow); else leftIndex.set(k, [lRow]); } const emptyLeft = {}; for (const key of columns.leftColumns ?? Object.keys(leftRows[0] ?? {})) emptyLeft[key] = ""; const result2 = []; for (const rRow of rightRows) { const k = rRow[rightKey] ?? ""; const matched = leftIndex.get(k) ?? []; if (matched.length > 0) { for (const lRow of matched) result2.push({ ...lRow, ...rRow }); } else { result2.push({ ...emptyLeft, ...rRow }); } } return result2; } const rightIndex = /* @__PURE__ */ new Map(); for (const rRow of rightRows) { const k = rRow[rightKey] ?? ""; const bucket = rightIndex.get(k); if (bucket) bucket.push(rRow); else rightIndex.set(k, [rRow]); } const result = []; const emptyRight = {}; for (const key of columns.rightColumns ?? Object.keys(rightRows[0] ?? {})) emptyRight[key] = ""; for (const lRow of leftRows) { const k = lRow[leftKey] ?? ""; const matched = rightIndex.get(k) ?? []; if (matched.length > 0) { for (const rRow of matched) { result.push({ ...lRow, ...rRow }); } } else if (joinType === "LEFT") { result.push({ ...lRow, ...emptyRight }); } } return result; } function assertJoinKeyAvailable(rows, key, savedColumns) { const missing = rows.length > 0 ? rows.some((row) => !Object.prototype.hasOwnProperty.call(row, key)) : savedColumns !== void 0 && !savedColumns.includes(key); if (missing) { throw new Error(`ArgumentError: JOIN key ${key} is not available in the materialized table.`); } } function applyFilter(rows, where, resolveFieldType, appliedKlikes, resolveFieldSemantics2) { if (where === null) return rows; return rows.filter((row) => evalWhere(where, row, resolveFieldType, appliedKlikes, resolveFieldSemantics2)); } function hasAggregateColumns(columns) { return columns.some( (c) => c.type === "AGGREGATE" || c.type === "ARITH_AGG_COL" || c.type === "STRFUNC_COL" && hasAggregateInStringFuncExpr2(c.expr) || c.type === "SCALAR_VALUE_COL" && scalarValueHasAggregate2(c.expr) ); } function applyGroupBy(rows, groupByKeys, columns, resolveAggSortKind) { const groups = /* @__PURE__ */ new Map(); for (const row of rows) { const key = groupByKeys.map((k) => evalGroupByKey(k, row)).join("\0"); const bucket = groups.get(key); if (bucket) bucket.push(row); else groups.set(key, [row]); } if (groups.size === 0 && groupByKeys.length === 0 && hasAggregateColumns(columns)) { groups.set("", []); } const result = []; for (const groupRows of groups.values()) { const outRow = { ...groupRows[0] }; for (const k of groupByKeys) { if (k.type === "ARITH_KEY") { outRow[arithColDefaultKey(k.expr)] = String(evalArithExpr(k.expr, groupRows[0])); } else if (k.type === "FUNC_KEY") { outRow[stringFuncDefaultKey(k.expr)] = evalStringFunc(k.expr, groupRows[0]); } } for (const col of columns) { if (col.type === "AGGREGATE") { const syntheticKey = aggregateSyntheticName(col.func, col.distinct, col.arg); const value = String(evalAggregate(col.func, col.distinct, col.arg, col.separator, groupRows, resolveAggSortKind)); outRow[col.alias ?? syntheticKey] = value; if (col.alias) outRow[syntheticKey] = value; } else if (col.type === "ARITH_AGG_COL") { const outputKey = col.alias ?? aggArithDefaultKey(col.expr); outRow[outputKey] = String(evalAggArithExpr(col.expr, groupRows, resolveAggSortKind)); } else if (col.type === "STRFUNC_COL" && hasAggregateInStringFuncExpr2(col.expr)) { const outputKey = col.alias ?? stringFuncDefaultKey(col.expr); const resolvedExpr = resolveAggInStringFuncExpr(col.expr, groupRows, resolveAggSortKind); outRow[outputKey] = evalStringFunc(resolvedExpr, outRow); } else if (col.type === "SCALAR_VALUE_COL" && scalarValueHasAggregate2(col.expr)) { const outputKey = col.alias ?? scalarValueDefaultKey(col.expr); const resolvedExpr = resolveAggInScalarValue(col.expr, groupRows, resolveAggSortKind); outRow[outputKey] = String(evalScalarValueExpr(resolvedExpr, outRow)); } } result.push(outRow); } return result; } function evalGroupByKey(key, row) { if (key.type === "FIELD_NAME") return row[key.name] ?? ""; if (key.type === "FUNC_KEY") return evalStringFunc(key.expr, row); return String(evalArithExpr(key.expr, row)); } function evalAggregate(func, distinct, arg, separator, rows, resolveAggSortKind) { if (arg.type === "WILDCARD") { return func === "COUNT" ? rows.length : 0; } const strValues = []; for (const row of rows) { let strVal; if (arg.type === "FIELD_REF") { const raw = row[arg.field]; if (raw === void 0 || raw === "" && func !== "MIN" && func !== "MAX") continue; strVal = raw; } else if (arg.type === "ARITH" || arg.type === "NUMBER" || arg.type === "STRING_FUNC") { const n = evalArithExpr(arg, row); if (isNaN(n)) continue; strVal = String(n); } else { const value = evalScalarValueExprNullable(arg, row); if (value === null) continue; if (value === "" && func !== "MIN" && func !== "MAX") continue; if (typeof value === "number" && Number.isNaN(value)) continue; strVal = String(value); } strValues.push(strVal); } const statistical = func === "STDDEV_POP" || func === "STDDEV_SAMP" || func === "VAR_POP" || func === "VAR_SAMP" || func === "MEDIAN"; const numericValues = statistical ? strValues.map((value) => { const numeric = Number(value); if (!Number.isFinite(numeric)) { throw new Error(`ArgumentError: ${func} \u306E\u5F15\u6570\u306B\u975E\u6570\u5024\u307E\u305F\u306F\u975E\u6709\u9650\u306E\u5024\u304C\u3042\u308A\u307E\u3059: ${value}`); } return numeric; }) : null; const eff = distinct ? statistical ? [...new Set(numericValues)] : [...new Set(strValues)] : statistical ? numericValues : strValues; if (func === "COUNT") return eff.length; if (func === "GROUP_CONCAT") return eff.join(separator ?? ","); const comparison = func === "MIN" || func === "MAX" || func === "MODE" ? resolveAggregateArgSemantics(arg, resolveAggSortKind) : void 0; const semantics = typeof comparison === "string" ? syntheticSemantics(comparison) : comparison ?? (arg.type === "FIELD_REF" || arg.type === "FIELD" || arg.type === "STRING" || arg.type === "CONCAT_OP" || arg.type === "CASE_WHEN" ? syntheticSemantics("string") : syntheticSemantics("number")); if (func === "MODE") { if (strValues.length === 0) return ""; const frequencies = /* @__PURE__ */ new Map(); for (const value of strValues) frequencies.set(value, (frequencies.get(value) ?? 0) + 1); let result = ""; let maxFrequency = 0; for (const [candidate, frequency] of frequencies) { if (frequency > maxFrequency) { result = candidate; maxFrequency = frequency; continue; } if (frequency !== maxFrequency) continue; const canonical = compareCanonicalValues(candidate, result, semantics); if (canonical < 0 || canonical === 0 && compareCodePointStrings(candidate, result) < 0) { result = candidate; } } return result; } if (func === "MIN" || func === "MAX") { const comparableValues = eff; if (comparableValues.length === 0) return 0; let result = comparableValues[0]; for (const candidate of comparableValues.slice(1)) { const cmp = compareCanonicalValues(candidate, result, semantics); if (func === "MAX" && cmp > 0 || func === "MIN" && cmp < 0) result = candidate; } return result; } const nums = statistical ? eff : eff.map(Number); switch (func) { case "SUM": return nums.reduce((a, b) => a + b, 0); case "AVG": return nums.length === 0 ? 0 : nums.reduce((a, b) => a + b, 0) / nums.length; case "MEDIAN": { if (nums.length === 0) return ""; const sorted = [...nums].sort((a, b) => a - b); const middle = Math.floor(sorted.length / 2); return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; } case "VAR_POP": case "VAR_SAMP": case "STDDEV_POP": case "STDDEV_SAMP": { const sample = func === "VAR_SAMP" || func === "STDDEV_SAMP"; if (nums.length === 0 || sample && nums.length < 2) return ""; const origin = nums[0]; let count = 0; let mean = 0; let m2 = 0; for (const rawValue of nums) { const value = rawValue - origin; count++; const delta = value - mean; mean += delta / count; m2 += delta * (value - mean); } const variance = Math.max(0, m2 / (sample ? count - 1 : count)); return func === "STDDEV_POP" || func === "STDDEV_SAMP" ? Math.sqrt(variance) : variance; } } } function toAggregateFieldRef(field) { const dot = field.indexOf("."); return dot > 0 ? { type: "FIELD", tableAlias: field.slice(0, dot), field: field.slice(dot + 1) } : { type: "FIELD", tableAlias: null, field }; } function evalAggArithExpr(node, rows, resolveAggSortKind) { if (node.type === "NUMBER") return node.value; if (node.type === "AGG_REF") return Number(evalAggregate(node.func, node.distinct, node.arg, node.separator, rows, resolveAggSortKind)); const l = evalAggArithExpr(node.left, rows, resolveAggSortKind); const r = evalAggArithExpr(node.right, rows, resolveAggSortKind); switch (node.op) { case "+": return l + r; case "-": return l - r; case "*": return l * r; case "/": return r !== 0 ? l / r : NaN; case "%": return r !== 0 ? l % r : NaN; } } function aggArithDefaultKey(node) { return aggregateOperandLabel(node); } function resolveAggregateArgSemantics(arg, resolver) { if (arg.type === "FIELD_REF") return resolver?.(toAggregateFieldRef(arg.field)) ?? "string"; if (arg.type === "FIELD") return resolver?.(arg) ?? "string"; if (arg.type === "NUMBER" || arg.type === "ARITH" || arg.type === "SCALAR_ARITH") return "number"; if (arg.type === "STRING" || arg.type === "CONCAT_OP" || arg.type === "VARIABLE") return "string"; if (arg.type === "STRING_FUNC") { const numeric = /* @__PURE__ */ new Set(["LENGTH", "LENGTH_CHAR", "INSTR", "ROUND", "FLOOR", "CEIL", "TRUNCATE", "YEAR", "MONTH", "DAY", "DATEDIFF", "ABS", "MOD", "POWER", "SQRT", "DAYOFWEEK", "QUARTER", "WEEK"]); if (arg.func === "CAST") return arg.args[1]?.type === "STRING" && arg.args[1].value === "NUMBER" ? "number" : "string"; return numeric.has(arg.func) ? "number" : "string"; } const results = [...arg.branches.map((branch) => branch.result), ...arg.elseResult === null ? [] : [arg.elseResult]].filter((result) => result.type !== "ARRAY").map((result) => resolveAggregateArgSemantics(result, resolver)); if (results.length === 0 || results.some((result) => result === void 0)) return "string"; const kinds = results.map((result) => typeof result === "string" ? result : result.compareMode === "number" || result.compareMode === "recordNumber" ? "number" : "string"); if (!kinds.every((kind) => kind === kinds[0])) return "string"; const first = results[0]; return results.every((result) => JSON.stringify(result) === JSON.stringify(first)) ? first : kinds[0]; } function applyHaving(rows, having, resolveFieldType, resolveFieldSemantics2) { if (having === null) return rows; return rows.filter((row) => evalWhere(having, row, resolveFieldType, void 0, resolveFieldSemantics2)); } function applyDistinct(rows, columns) { if (rows.length === 0) return rows; const keyFor = buildDistinctKeyBuilder(rows, columns); const seen = /* @__PURE__ */ new Set(); return rows.filter((row) => { const key = keyFor(row); if (seen.has(key)) return false; seen.add(key); return true; }); } function buildDistinctKeyBuilder(rows, columns) { if (columns.some((c) => c.type === "WILDCARD")) { const allKeys = /* @__PURE__ */ new Set(); for (const row of rows) { for (const k of Object.keys(row)) allKeys.add(k); } const keys = [...allKeys].sort(); return (row) => JSON.stringify(keys.map((k) => row[k] !== void 0 ? row[k] : null)); } let sortedParentKeys = []; if (columns.some((c) => c.type === "PARENT_WILDCARD")) { const parentKeys = /* @__PURE__ */ new Set(); for (const row of rows) { for (const k of Object.keys(row)) { if (k.startsWith("_p.")) parentKeys.add(k); } } sortedParentKeys = [...parentKeys].sort(); } return (row) => { const values = []; for (const col of columns) { if (col.type === "FIELD") { values.push(row[col.field] ?? ""); continue; } if (col.type === "WINDOW_COL") { values.push(row[col.alias] ?? ""); continue; } if (col.type === "PARENT_WILDCARD") { for (const k of sortedParentKeys) { values.push(row[k] !== void 0 ? row[k] : null); } } } return JSON.stringify(values); }; } function applyOrderBy(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) { if (orderBy.length === 0) return rows; return sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator).rows.map((item) => item.row); } function sortDecoratedRows(rows, orderBy, optionOrders, sortKinds, fieldSemantics2, aliasEvaluator) { const keyMeta = orderBy.map(({ key }) => { if (key.type === "ARITH_KEY") return { semantics: syntheticSemantics("number") }; if (key.type === "FUNC_KEY") { return { semantics: syntheticSemantics(NUMERIC_ORDER_FUNCTIONS.has(key.expr.func) ? "number" : "string") }; } const semantics = fieldSemantics2?.get(key.name); if (semantics) return { semantics }; const orderMap = optionOrders?.get(key.name); if (orderMap) { return { semantics: { fieldType: "MULTI_SELECT", compareMode: "option", inSubtable: false, requiresCollectionOperators: false, optionOrder: orderMap } }; } return { semantics: syntheticSemantics(sortKinds?.get(key.name) ?? "string") }; }); const decorated = rows.map((row) => ({ row, keys: orderBy.map(({ key }, i) => { const s = evalOrderKey(key, row, aliasEvaluator); return { s }; }) })); const compare = (a, b) => compareDecoratedRows(a, b, orderBy, keyMeta); decorated.sort(compare); return { rows: decorated, compare }; } function compareDecoratedRows(a, b, orderBy, keyMeta) { for (let i = 0; i < orderBy.length; i++) { const cmp = compareSortKeys(a.keys[i], b.keys[i], keyMeta[i]); if (cmp !== 0) return orderBy[i].direction === "ASC" ? cmp : -cmp; } return 0; } function compareSortKeys(a, b, meta3) { return compareCanonicalValues(a.s, b.s, meta3.semantics); } var NUMERIC_ORDER_FUNCTIONS = /* @__PURE__ */ new Set([ "LENGTH", "LENGTH_CHAR", "INSTR", "ROUND", "FLOOR", "CEIL", "TRUNCATE", "YEAR", "MONTH", "DAY", "DATEDIFF", "ABS", "MOD", "POWER", "SQRT", "DAYOFWEEK", "QUARTER", "WEEK" ]); function evalOrderKey(key, row, aliasEvaluator) { switch (key.type) { case "FIELD_NAME": return aliasEvaluator?.(key.name, row) ?? row[key.name] ?? ""; case "ARITH_KEY": return String(evalArithExpr(key.expr, row)); case "FUNC_KEY": return evalStringFunc(key.expr, row); } } function buildOrderByAliasEvaluator(columns, scalarCache, resolveFieldType, resolveFieldSemantics2) { const evaluators = /* @__PURE__ */ new Map(); for (const [columnIndex, column] of columns.entries()) { if (!("alias" in column) || column.alias === null) continue; const alias = column.alias; switch (column.type) { case "FIELD": evaluators.set(alias, (row) => resolveFieldRef(row, column.field)); break; case "LITERAL_COL": evaluators.set(alias, () => column.value); break; case "AGGREGATE": { const source = aggregateSyntheticName(column.func, column.distinct, column.arg); evaluators.set(alias, (row) => row[alias] ?? row[source] ?? "0"); break; } case "ARITH_AGG_COL": { const source = aggArithDefaultKey(column.expr); evaluators.set(alias, (row) => row[alias] ?? row[source] ?? "0"); break; } case "WINDOW_COL": evaluators.set(alias, (row) => row[alias] ?? ""); break; case "ARITH_COL": evaluators.set(alias, (row) => String(evalArithExpr(column.expr, row))); break; case "STRFUNC_COL": { const source = stringFuncDefaultKey(column.expr); evaluators.set(alias, (row) => hasAggregateInStringFuncExpr2(column.expr) ? row[alias] ?? row[source] ?? evalStringFunc(column.expr, row, resolveFieldType, resolveFieldSemantics2) : evalStringFunc(column.expr, row, resolveFieldType, resolveFieldSemantics2)); break; } case "CASE_COL": evaluators.set(alias, (row) => evalCaseWhen(column.expr, row, resolveFieldType, resolveFieldSemantics2)); break; case "SCALAR_VALUE_COL": { const source = scalarValueDefaultKey(column.expr); evaluators.set(alias, (row) => scalarValueHasAggregate2(column.expr) ? row[alias] ?? row[source] ?? "" : String(evalScalarValueExpr(column.expr, row, resolveFieldType, resolveFieldSemantics2))); break; } case "SCALAR_SUBQUERY_COL": evaluators.set(alias, () => scalarCache?.get(columnIndex) ?? ""); break; case "VARIABLE_COL": break; } } return (name, row) => evaluators.get(name)?.(row); } function applyWindow(rows, columns, optionOrders, sortKinds, fieldSemantics2) { const windows = columns.filter((column) => column.type === "WINDOW_COL"); if (rows.length === 0 || windows.length === 0) return rows; for (const window of windows) { const partitions = /* @__PURE__ */ new Map(); for (const row of rows) { const key = JSON.stringify(window.partitionBy.map((ref) => resolveWindowField(row, ref))); const partition = partitions.get(key); if (partition) partition.push(row); else partitions.set(key, [row]); } for (const partition of partitions.values()) { const sortedResult = sortDecoratedRows(partition, window.orderBy, optionOrders, sortKinds, fieldSemantics2); const sorted = sortedResult.rows; let rank = 1; let denseRank = 1; for (let index = 0; index < sorted.length; index++) { if (index > 0 && sortedResult.compare(sorted[index - 1], sorted[index]) !== 0) { rank = index + 1; denseRank++; } const value = window.func === "ROW_NUMBER" ? index + 1 : window.func === "RANK" ? rank : denseRank; sorted[index].row[window.alias] = String(value); } } } return rows; } function resolveWindowField(row, ref) { const name = ref.tableAlias ? `${ref.tableAlias}.${ref.field}` : ref.field; return resolveFieldRef(row, name); } function applyLimit(rows, limit, offset) { const start = offset ?? 0; if (limit === null) return rows.slice(start); return rows.slice(start, start + limit); } function project(rows, columns, scalarCache, resolveFieldType, sourceColumns, resolveFieldSemantics2, hiddenQualifiedAliases) { if (columns.length === 1 && columns[0].type === "WILDCARD") { const projected2 = rows.map((row) => stripHiddenQualifiedColumns( stripParentShortcutColumns(row), hiddenQualifiedAliases )); const cols = projected2.length > 0 ? Object.keys(projected2[0]) : [...sourceColumns ?? []]; return { rows: projected2, columns: cols }; } const defaultFieldKeys = buildDefaultFieldOutputKeys(columns); const hasWildcard = columns.some( (col) => col.type === "WILDCARD" || col.type === "PARENT_WILDCARD" ); const outputKeys = hasWildcard ? null : computeOutputKeys(columns, defaultFieldKeys); const orderedKeys = outputKeys ?? []; if (hasWildcard && rows.length === 0) { return { rows: [], columns: computeExplicitOutputKeys(columns, defaultFieldKeys) }; } const projected = rows.map((row, rowIdx) => { const out = {}; for (const [colIdx, col] of columns.entries()) { switch (col.type) { case "VARIABLE_COL": throw new Error(`internal error: unresolved SELECT variable @${col.name}`); case "WILDCARD": Object.assign(out, stripHiddenQualifiedColumns( stripParentShortcutColumns(row), hiddenQualifiedAliases )); break; case "PARENT_WILDCARD": { const parentKeys = Object.keys(row).filter((k) => k.startsWith("_p.")).sort(); for (const key of parentKeys) { out[key] = row[key] ?? ""; if (rowIdx === 0) orderedKeys.push(key); } break; } case "FIELD": { const key = outputKeys?.[colIdx] ?? col.alias ?? defaultFieldKeys.get(colIdx) ?? col.field; out[key] = resolveFieldRef(row, col.field); if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "LITERAL_COL": { const key = outputKeys?.[colIdx] ?? col.alias ?? `'${col.value}'`; out[key] = col.value; if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "AGGREGATE": { const srcKey = aggregateSyntheticName(col.func, col.distinct, col.arg); const dstKey = outputKeys?.[colIdx] ?? col.alias ?? srcKey; out[dstKey] = row[col.alias ?? srcKey] ?? row[srcKey] ?? "0"; if (outputKeys === null && rowIdx === 0) orderedKeys.push(dstKey); break; } case "ARITH_AGG_COL": { const key = outputKeys?.[colIdx] ?? col.alias ?? aggArithDefaultKey(col.expr); out[key] = row[key] ?? "0"; if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "ARITH_COL": { const val = evalArithExpr(col.expr, row); const key = outputKeys?.[colIdx] ?? col.alias ?? arithColDefaultKey(col.expr); out[key] = String(val); if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "CASE_COL": { const key = outputKeys?.[colIdx] ?? col.alias ?? "case"; out[key] = evalCaseWhen(col.expr, row, resolveFieldType, resolveFieldSemantics2); if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "STRFUNC_COL": { const key = outputKeys?.[colIdx] ?? col.alias ?? stringFuncDefaultKey(col.expr); if (hasAggregateInStringFuncExpr2(col.expr)) { const srcKey = stringFuncDefaultKey(col.expr); out[key] = row[col.alias ?? srcKey] ?? row[srcKey] ?? evalStringFunc(col.expr, row, resolveFieldType, resolveFieldSemantics2); } else { out[key] = evalStringFunc(col.expr, row, resolveFieldType, resolveFieldSemantics2); } if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "SCALAR_VALUE_COL": { const key = outputKeys?.[colIdx] ?? col.alias ?? scalarValueDefaultKey(col.expr); const srcKey = scalarValueDefaultKey(col.expr); out[key] = scalarValueHasAggregate2(col.expr) ? row[col.alias ?? srcKey] ?? row[srcKey] ?? "" : String(evalScalarValueExpr(col.expr, row, resolveFieldType, resolveFieldSemantics2)); if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "SCALAR_SUBQUERY_COL": { const key = outputKeys?.[colIdx] ?? col.alias ?? "(subquery)"; out[key] = scalarCache?.get(colIdx) ?? ""; if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } case "WINDOW_COL": { const key = outputKeys?.[colIdx] ?? col.alias; out[key] = row[col.alias] ?? ""; if (outputKeys === null && rowIdx === 0) orderedKeys.push(key); break; } } } return out; }); return { rows: projected, columns: orderedKeys }; } function computeOutputKeys(columns, defaultFieldKeys) { return columns.map((col, colIdx) => computeOutputKey(col, colIdx, defaultFieldKeys)); } function computeExplicitOutputKeys(columns, defaultFieldKeys) { const keys = []; const seen = /* @__PURE__ */ new Set(); for (const [colIdx, col] of columns.entries()) { if (col.type === "WILDCARD" || col.type === "PARENT_WILDCARD") continue; const key = computeOutputKey(col, colIdx, defaultFieldKeys); if (!seen.has(key)) { seen.add(key); keys.push(key); } } return keys; } function computeOutputKey(col, colIdx, defaultFieldKeys) { switch (col.type) { case "VARIABLE_COL": throw new Error(`internal error: unresolved SELECT variable @${col.name}`); case "FIELD": return col.alias ?? defaultFieldKeys.get(colIdx) ?? col.field; case "LITERAL_COL": return col.alias ?? `'${col.value}'`; case "AGGREGATE": return col.alias ?? aggregateSyntheticName(col.func, col.distinct, col.arg); case "ARITH_AGG_COL": return col.alias ?? aggArithDefaultKey(col.expr); case "ARITH_COL": return col.alias ?? arithColDefaultKey(col.expr); case "CASE_COL": return col.alias ?? "case"; case "STRFUNC_COL": return col.alias ?? stringFuncDefaultKey(col.expr); case "SCALAR_VALUE_COL": return col.alias ?? scalarValueDefaultKey(col.expr); case "SCALAR_SUBQUERY_COL": return col.alias ?? "(subquery)"; case "WINDOW_COL": return col.alias; case "WILDCARD": case "PARENT_WILDCARD": throw new Error("internal: computeOutputKey received a wildcard column"); } } function buildDefaultFieldOutputKeys(columns) { const qualifierCollisionCount = /* @__PURE__ */ new Map(); for (const col of columns) { if (col.type !== "FIELD" || col.alias) continue; const unqualified = stripTableQualifier(col.field); qualifierCollisionCount.set(unqualified, (qualifierCollisionCount.get(unqualified) ?? 0) + 1); } const keys = /* @__PURE__ */ new Map(); for (const [idx, col] of columns.entries()) { if (col.type !== "FIELD" || col.alias) continue; const unqualified = stripTableQualifier(col.field); const duplicate = (qualifierCollisionCount.get(unqualified) ?? 0) > 1; const hasTableQualifier = col.field.includes(".") && !col.field.startsWith("_p."); keys.set(idx, duplicate && hasTableQualifier ? col.field : unqualified); } return keys; } function stripTableQualifier(field) { if (field.startsWith("_p.")) return field; const dot = field.indexOf("."); if (dot <= 0) return field; const unqualified = field.slice(dot + 1); return unqualified || field; } function stripParentShortcutColumns(row) { const out = {}; for (const [k, v] of Object.entries(row)) { if (k.startsWith("_p.")) continue; out[k] = v; } return out; } function arithColDefaultKey(expr) { const nodeLabel = (n) => { if (n.type === "FIELD_REF") return n.field; if (n.type === "NUMBER") return numberLiteralText(n); if (n.type === "STRING_FUNC") return stringFuncDefaultKey(n); return `(${nodeLabel(n.left)}${n.op}${nodeLabel(n.right)})`; }; if (expr.type === "ARITH") { return `${nodeLabel(expr.left)}${expr.op}${nodeLabel(expr.right)}`; } return nodeLabel(expr); } function stringFuncDefaultKey(expr) { const argStrs = expr.args.map((a) => { if (a.type === "AGG_REF" || a.type === "AGG_ARITH") return aggArithDefaultKey(a); return scalarValueDefaultKey(a); }); return `${expr.func}(${argStrs.join(",")})`; } function scalarValueDefaultKey(expr) { switch (expr.type) { case "STRING": return `'${expr.value}'`; case "NUMBER": return numberLiteralText(expr); case "VARIABLE": return `@${expr.name}`; case "FIELD": return expr.tableAlias ? `${expr.tableAlias}.${expr.field}` : expr.field; case "STRING_FUNC": return stringFuncDefaultKey(expr); case "CASE_WHEN": return "case"; case "SCALAR_ARITH": return `${scalarValueDefaultKey(expr.left)}${expr.op}${scalarValueDefaultKey(expr.right)}`; case "CONCAT_OP": return `${scalarValueDefaultKey(expr.left)}||${scalarValueDefaultKey(expr.right)}`; } } function hasAggregateInStringFuncArg(arg) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") return true; return scalarValueHasAggregate2(arg); } function scalarValueHasAggregate2(expr) { if (expr.type === "STRING_FUNC") return hasAggregateInStringFuncExpr2(expr); if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { return scalarValueHasAggregate2(expr.left) || scalarValueHasAggregate2(expr.right); } if (expr.type === "CASE_WHEN") { return expr.branches.some((branch) => caseResultHasAggregate2(branch.result)) || expr.elseResult !== null && caseResultHasAggregate2(expr.elseResult); } return false; } function caseResultHasAggregate2(result) { if (result.type === "ARRAY" || result.type === "FIELD_REF" || result.type === "ARITH") return false; return scalarValueHasAggregate2(result); } function hasAggregateInStringFuncExpr2(expr) { return expr.args.some((arg) => hasAggregateInStringFuncArg(arg)); } function resolveAggInStringFuncArg(arg, rows, resolveAggSortKind) { if (arg.type === "AGG_REF") { const value = evalAggregate(arg.func, arg.distinct, arg.arg, arg.separator, rows, resolveAggSortKind); return typeof value === "number" ? { type: "NUMBER", value, raw: String(value) } : { type: "STRING", value }; } if (arg.type === "AGG_ARITH") { const value = evalAggArithExpr(arg, rows, resolveAggSortKind); return { type: "NUMBER", value, raw: String(value) }; } if (arg.type === "STRING_FUNC") { return resolveAggInStringFuncExpr(arg, rows, resolveAggSortKind); } return resolveAggInScalarValue(arg, rows, resolveAggSortKind); } function resolveAggInScalarValue(expr, rows, resolveAggSortKind) { if (expr.type === "STRING_FUNC") return resolveAggInStringFuncExpr(expr, rows, resolveAggSortKind); if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { return { ...expr, left: resolveAggInScalarValue(expr.left, rows, resolveAggSortKind), right: resolveAggInScalarValue(expr.right, rows, resolveAggSortKind) }; } return expr; } function resolveAggInStringFuncExpr(expr, rows, resolveAggSortKind) { return { type: "STRING_FUNC", func: expr.func, args: expr.args.map((arg) => resolveAggInStringFuncArg(arg, rows, resolveAggSortKind)) }; } function stripHiddenQualifiedColumns(row, hiddenQualifiedAliases) { if (!hiddenQualifiedAliases || hiddenQualifiedAliases.size === 0) return row; const out = {}; for (const [key, value] of Object.entries(row)) { if ([...hiddenQualifiedAliases].some((alias) => key.startsWith(`${alias}.`))) continue; out[key] = value; } return out; } function flattenedColumns(columns, alias) { if (columns === void 0) return void 0; return alias ? columns.flatMap((column) => [`${alias}.${column}`, column]) : [...columns]; } function mergeKnownColumns(left, right, rows) { if (left === void 0 && right === void 0 && rows.length === 0) return void 0; return [.../* @__PURE__ */ new Set([ ...left ?? [], ...right ?? [], ...Object.keys(rows[0] ?? {}) ])]; } function deriveOutputOrderSemantics(columns) { const result = /* @__PURE__ */ new Map(); for (const column of columns) { if (!("alias" in column) || !column.alias) continue; if (column.type === "ARITH_COL" || column.type === "ARITH_AGG_COL" || column.type === "WINDOW_COL") { result.set(column.alias, syntheticSemantics("number")); } else if (column.type === "AGGREGATE") { if (column.func === "COUNT" || column.func === "SUM" || column.func === "AVG" || column.func === "STDDEV_POP" || column.func === "STDDEV_SAMP" || column.func === "VAR_POP" || column.func === "VAR_SAMP" || column.func === "MEDIAN") { result.set(column.alias, syntheticSemantics("number")); } else if (column.func === "GROUP_CONCAT") { result.set(column.alias, syntheticSemantics("string")); } } else if (column.type === "LITERAL_COL" || column.type === "CASE_COL" || column.type === "SCALAR_SUBQUERY_COL" || column.type === "SCALAR_VALUE_COL") { result.set(column.alias, syntheticSemantics("string")); } else if (column.type === "STRFUNC_COL") { result.set(column.alias, syntheticSemantics(NUMERIC_ORDER_FUNCTIONS.has(column.expr.func) ? "number" : "string")); } } return result; } function runFullScan(input) { const { stmt, tables, scalarCache, optionOrders, sortKinds, orderSemantics, fieldTypeResolver, fieldSemanticsResolver, havingFieldTypeResolver, havingFieldSemanticsResolver, aggregateSortKindResolver, appliedKlikes, sourceColumns, tableColumns, hiddenQualifiedAliases } = input; const effectiveOrderSemantics = deriveOutputOrderSemantics(stmt.columns); for (const [key, value] of orderSemantics ?? []) effectiveOrderSemantics.set(key, value); let rows = []; const mainAlias = stmt.from.alias; const mainRecords = tables.get(mainAlias) ?? tables.get(null) ?? []; rows = mainRecords.map((r) => flatten(r, mainAlias)); let knownColumns = mergeKnownColumns( flattenedColumns(tableColumns?.get(mainAlias), mainAlias), void 0, rows ); for (const join of stmt.joins) { const rightAlias = join.table.alias; const rightRecords = tables.get(rightAlias) ?? []; const rightRows = rightRecords.map((r) => flatten(r, rightAlias)); const rightColumns = mergeKnownColumns( flattenedColumns(tableColumns?.get(rightAlias), rightAlias), void 0, rightRows ); rows = applyJoin(rows, rightRows, join, { leftColumns: knownColumns, rightColumns }); knownColumns = mergeKnownColumns(knownColumns, rightColumns, rows); } rows = applyFilter(rows, stmt.where, fieldTypeResolver, appliedKlikes, fieldSemanticsResolver); if (stmt.groupBy.length > 0 || hasAggregateColumns(stmt.columns)) { rows = applyGroupBy(rows, stmt.groupBy, stmt.columns, aggregateSortKindResolver); } rows = applyHaving(rows, stmt.having, havingFieldTypeResolver, havingFieldSemanticsResolver); rows = applyWindow(rows, stmt.columns, optionOrders, sortKinds, effectiveOrderSemantics); if (stmt.distinct) { rows = applyDistinct(rows, stmt.columns); } rows = applyOrderBy( rows, stmt.orderBy, optionOrders, sortKinds, effectiveOrderSemantics, buildOrderByAliasEvaluator(stmt.columns, scalarCache, fieldTypeResolver, fieldSemanticsResolver) ); rows = applyLimit(rows, stmt.limit, stmt.offset); return project( rows, stmt.columns, scalarCache, fieldTypeResolver, sourceColumns, fieldSemanticsResolver, hiddenQualifiedAliases ); } // src/converter/subtableAdapter.ts init_define_KSQL_DOCS(); function expandSubtableRecords(parents, subtableCode) { const rows = []; for (const parent of parents) { const parentId = toFlatString(parent["$id"]?.value); const tableValue = readTableRows(parent[subtableCode]?.value); if (tableValue.length === 0) continue; for (let i = 0; i < tableValue.length; i++) { const row = tableValue[i]; const out = { _pid: { value: parentId }, _rid: { value: row.id ?? "" }, _idx: { value: String(i) } }; for (const [field, fieldValue] of Object.entries(parent)) { if (field === subtableCode) continue; const flat = toFlatString(fieldValue?.value); out[`_p.${field}`] = { value: flat }; } for (const [field, cell] of Object.entries(row.value ?? {})) { out[field] = { value: toFlatString(cell?.value) }; } rows.push(out); } } return rows; } function readTableRows(value) { if (!Array.isArray(value)) return []; return value.filter((item) => !!item && typeof item === "object"); } function toFlatString(value) { if (value === null || value === void 0) return ""; if (typeof value === "string") return value; if (typeof value === "number" || typeof value === "boolean") return String(value); try { return JSON.stringify(value); } catch { return String(value); } } // src/core/dmlPrevalidation.ts init_define_KSQL_DOCS(); function collectDmlPrevalidationSnapshotFields(fieldIndex) { return [ "$id", .../* @__PURE__ */ new Set([ ...fieldIndex.topLevel.map((field) => field.code).filter((code) => code !== "$id" && code !== "$revision"), ...fieldIndex.subtables.keys() ]) ]; } function buildDmlValidationPostImage(snapshot, sparseRecord) { const postImage = deepClone(snapshot); for (const [field, cell] of Object.entries(sparseRecord)) { postImage[field] = deepClone(cell); } return postImage; } function mergeDmlCandidateValidation(input) { const errors = [ ...input.preErrors.map((row) => normalizePlainError(row)), ...input.postImageErrors.map((row) => normalizePlainError(row, row["$err_subtable"] !== "")), ...input.checkErrors.map((row) => normalizePlainError(row)) ]; const invalidRowNumbers = /* @__PURE__ */ new Set(); if (errors.length > 0) invalidRowNumbers.add(input.rowNumber); const writeRecord = {}; for (const field of new Set(input.setFields)) { if (!Object.prototype.hasOwnProperty.call(input.normalizedPostImage, field)) { throw new Error(`InternalError: normalized post-image is missing SET field: ${field}`); } writeRecord[field] = deepClone(input.normalizedPostImage[field]); } return { errors, invalidRows: invalidRowNumbers.size, invalidRowNumbers, writeRecord }; } function normalizePlainError(row, childCell = false) { return { ...row, $err_value: childCell ? row["$err_value"] ?? "" : "", $err_subtable: childCell ? row["$err_subtable"] ?? "" : "", $err_subrow: childCell ? row["$err_subrow"] ?? "" : "", $err_subrow_id: childCell ? row["$err_subrow_id"] ?? "" : "" }; } function deepClone(value, seen = /* @__PURE__ */ new Map()) { if (value === null || typeof value !== "object") return value; const object3 = value; const existing = seen.get(object3); if (existing !== void 0) return existing; if (Array.isArray(value)) { const clone3 = []; seen.set(object3, clone3); for (const item of value) clone3.push(deepClone(item, seen)); return clone3; } const clone2 = {}; seen.set(object3, clone2); for (const [key, child] of Object.entries(value)) clone2[key] = deepClone(child, seen); return clone2; } // src/core/optimization/whereCapability.ts init_define_KSQL_DOCS(); var RANGE_AND_EQUALITY = ["=", "!=", ">", "<", ">=", "<="]; var EQUALITY_IN = ["=", "!=", "in", "not in"]; var NATIVE_OPERATORS = /* @__PURE__ */ new Map([ ["RECORD_NUMBER", /* @__PURE__ */ new Set([...RANGE_AND_EQUALITY, "in", "not in"])], ["__ID__", /* @__PURE__ */ new Set([...RANGE_AND_EQUALITY, "in", "not in"])], ["CREATOR", /* @__PURE__ */ new Set(["in", "not in"])], ["MODIFIER", /* @__PURE__ */ new Set(["in", "not in"])], ["CREATED_TIME", new Set(RANGE_AND_EQUALITY)], ["UPDATED_TIME", new Set(RANGE_AND_EQUALITY)], ["DATE", new Set(RANGE_AND_EQUALITY)], ["TIME", new Set(RANGE_AND_EQUALITY)], ["DATETIME", new Set(RANGE_AND_EQUALITY)], ["SINGLE_LINE_TEXT", /* @__PURE__ */ new Set(["=", "!=", "in", "not in", "like", "not like"])], ["LINK", /* @__PURE__ */ new Set(["=", "!=", "in", "not in", "like", "not like"])], ["NUMBER", /* @__PURE__ */ new Set([...RANGE_AND_EQUALITY, "in", "not in"])], ["CALC", /* @__PURE__ */ new Set([...RANGE_AND_EQUALITY, "in", "not in"])], ["MULTI_LINE_TEXT", /* @__PURE__ */ new Set(["like", "not like"])], ["RICH_TEXT", /* @__PURE__ */ new Set(["like", "not like"])], ["CHECK_BOX", /* @__PURE__ */ new Set(["in", "not in"])], ["RADIO_BUTTON", /* @__PURE__ */ new Set(["in", "not in"])], ["DROP_DOWN", /* @__PURE__ */ new Set(["in", "not in"])], ["MULTI_SELECT", /* @__PURE__ */ new Set(["in", "not in"])], ["FILE", /* @__PURE__ */ new Set(["like", "not like"])], ["USER_SELECT", /* @__PURE__ */ new Set(["in", "not in"])], ["ORGANIZATION_SELECT", /* @__PURE__ */ new Set(["in", "not in"])], ["GROUP_SELECT", /* @__PURE__ */ new Set(["in", "not in"])], ["STATUS", new Set(EQUALITY_IN)] ]); var LOCAL_SCALAR_TYPES = /* @__PURE__ */ new Set([ "RECORD_NUMBER", "__ID__", "CREATOR", "MODIFIER", "CREATED_TIME", "UPDATED_TIME", "DATE", "TIME", "DATETIME", "SINGLE_LINE_TEXT", "LINK", "NUMBER", "CALC", "MULTI_LINE_TEXT", "RICH_TEXT", "RADIO_BUTTON", "DROP_DOWN", "STATUS", // 一時表・CTE・式列は kintone REST へは送らず、共有ローカル評価器で扱う。 "KSQL_STRING", "KSQL_NUMBER", "KSQL_BOOLEAN" ]); var LOCAL_COLLECTION_TYPES = /* @__PURE__ */ new Set([ "CHECK_BOX", "MULTI_SELECT", "FILE", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT", "STATUS_ASSIGNEE", "CATEGORY" ]); function nativeWhereOperatorsForType(fieldType) { return NATIVE_OPERATORS.get(fieldType) ?? /* @__PURE__ */ new Set(); } function classifyWhereCapability(where, resolveField2) { if (where === null) { return { capability: "EXACT_PUSHDOWN", reasons: [{ code: "WHERE_EXACT" }] }; } return classifyNode(where, resolveField2); } function classifyNode(where, resolveField2) { switch (where.type) { case "BOOLEAN": return { capability: "LOCAL_ONLY", reasons: [{ code: "WHERE_EXPRESSION_LOCAL_ONLY" }] }; case "BINARY": return classifyBinary(where.op, where.left, where.right.type, resolveField2); case "NULL_CHECK": if (where.field.type !== "FIELD") return localExpression(); return classifyLocalOnlyField(where.field, where.not ? "IS NOT NULL" : "IS NULL", resolveField2); case "EXISTS": return localExpression(); case "GROUP": return classifyNode(where.expr, resolveField2); case "NOT": { const inner = classifyNode(where.expr, resolveField2); return inner.capability === "SUPERSET_PREFILTER" ? { capability: "LOCAL_ONLY", reasons: [{ code: "WHERE_EXPRESSION_LOCAL_ONLY" }] } : inner; } case "LOGICAL": { const left = classifyNode(where.left, resolveField2); const right = classifyNode(where.right, resolveField2); return combineLogical(where.op, left, right); } } } function classifyBinary(op, left, rightType, resolveField2) { if (left.type !== "FIELD") return localExpression(); const semantics = resolveField2(left); if (!semantics) { return unsupported2("WHERE_FIELD_UNRESOLVED", left.field, void 0, normalizeOperator(op)); } if (!hasLocalContract(semantics.fieldType, op)) { return unsupported2("WHERE_OPERATOR_UNSUPPORTED", left.field, semantics.fieldType, normalizeOperator(op)); } const nativeOp = normalizeOperator(op); const native = nativeWhereOperatorsForType(semantics.fieldType); const rightCanPush = rightType === "STRING" || rightType === "NUMBER" || rightType === "IN_LIST" || rightType === "KINTONE_FUNC"; const structureAllows = !semantics.requiresCollectionOperators || nativeOp !== "=" && nativeOp !== "!="; const sqlLikeIsResidual = op === "LIKE" || op === "NOT_LIKE"; if (rightCanPush && structureAllows && native.has(nativeOp) && !sqlLikeIsResidual) { return { capability: "EXACT_PUSHDOWN", reasons: [{ code: "WHERE_EXACT", field: left.field, fieldType: semantics.fieldType, operator: nativeOp }] }; } return { capability: "LOCAL_ONLY", reasons: [{ code: "WHERE_RESIDUAL", field: left.field, fieldType: semantics.fieldType, operator: nativeOp }] }; } function classifyLocalOnlyField(field, operator, resolveField2) { const semantics = resolveField2(field); if (!semantics) return unsupported2("WHERE_FIELD_UNRESOLVED", field.field, void 0, operator); if (!LOCAL_SCALAR_TYPES.has(semantics.fieldType) && !LOCAL_COLLECTION_TYPES.has(semantics.fieldType)) { return unsupported2("WHERE_OPERATOR_UNSUPPORTED", field.field, semantics.fieldType, operator); } return { capability: "LOCAL_ONLY", reasons: [{ code: "WHERE_RESIDUAL", field: field.field, fieldType: semantics.fieldType, operator }] }; } function hasLocalContract(fieldType, op) { if (LOCAL_SCALAR_TYPES.has(fieldType)) return true; if (!LOCAL_COLLECTION_TYPES.has(fieldType)) return false; return op === "=" || op === "!=" || op === "<>" || op === "IN" || op === "NOT_IN" || op === "LIKE" || op === "NOT_LIKE" || op === "KLIKE" || op === "NOT_KLIKE"; } function normalizeOperator(op) { switch (op) { case "<>": return "!="; case "IN": return "in"; case "NOT_IN": return "not in"; case "LIKE": case "KLIKE": return "like"; case "NOT_LIKE": case "NOT_KLIKE": return "not like"; default: return op; } } function combineLogical(op, left, right) { const reasons = [...left.reasons, ...right.reasons]; if (left.capability === "UNSUPPORTED" || right.capability === "UNSUPPORTED") { return { capability: "UNSUPPORTED", reasons }; } if (left.capability === "EXACT_PUSHDOWN" && right.capability === "EXACT_PUSHDOWN") { return { capability: "EXACT_PUSHDOWN", reasons }; } if (op === "AND" && (left.capability === "EXACT_PUSHDOWN" || right.capability === "EXACT_PUSHDOWN" || left.capability === "SUPERSET_PREFILTER" || right.capability === "SUPERSET_PREFILTER")) { return { capability: "SUPERSET_PREFILTER", reasons: [{ code: "WHERE_SUPERSET_PREFILTER" }, ...reasons] }; } return { capability: "LOCAL_ONLY", reasons }; } function localExpression() { return { capability: "LOCAL_ONLY", reasons: [{ code: "WHERE_EXPRESSION_LOCAL_ONLY" }] }; } function unsupported2(code, field, fieldType, operator) { return { capability: "UNSUPPORTED", reasons: [{ code, field, fieldType, operator }] }; } // src/import/sourceLoader.ts init_define_KSQL_DOCS(); var IMPORT_MAX_BYTES = 10 * 1024 * 1024; var ImportSourceError = class extends Error { constructor(message) { super(`ImportSourceError: ${message}`); this.name = "ImportSourceError"; } }; function resolveImportSource(name, resolver) { if (!resolver) throw new ImportSourceError("IMPORT source capability is not available."); const handle = resolver(name); if (!handle) throw new ImportSourceError(`source "${name}" is not supplied.`); return handle; } async function loadImportSource(handle, cache) { let pending = cache.get(handle); if (!pending) { pending = handle.load().then((payload) => { if (!(payload.bytes instanceof Uint8Array)) throw new ImportSourceError("loader must return Uint8Array bytes."); if (payload.bytes.byteLength > IMPORT_MAX_BYTES) { throw new ImportSourceError(`source exceeds the ${IMPORT_MAX_BYTES} byte limit.`); } return payload; }); cache.set(handle, pending); } return pending; } // src/import/materializeDmlSource.ts init_define_KSQL_DOCS(); // src/import/csvDecoder.ts init_define_KSQL_DOCS(); function decodeImportText(bytes, encoding) { try { return new TextDecoder(encoding === "sjis" ? "shift_jis" : "utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, ""); } catch { throw new ImportSourceError(`invalid ${encoding.toUpperCase()} byte sequence.`); } } function parseRfc4180(text) { const records = []; let record2 = []; let cell = ""; let quoted = false; let afterQuote = false; let i = 0; const finishCell = () => { record2.push(cell); cell = ""; afterQuote = false; }; const finishRecord = () => { finishCell(); records.push(record2); record2 = []; }; while (i < text.length) { const ch = text[i]; if (quoted) { if (ch === '"') { if (text[i + 1] === '"') { cell += '"'; i += 2; continue; } quoted = false; afterQuote = true; i++; continue; } cell += ch; i++; continue; } if (afterQuote && ch !== "," && ch !== "\r" && ch !== "\n") { throw new ImportSourceError(`unexpected character after closing quote at offset ${i}.`); } if (ch === '"') { if (cell.length !== 0) throw new ImportSourceError(`quote in unquoted cell at offset ${i}.`); quoted = true; i++; continue; } if (ch === ",") { finishCell(); i++; continue; } if (ch === "\r" || ch === "\n") { if (ch === "\r" && text[i + 1] === "\n") i++; finishRecord(); i++; continue; } cell += ch; i++; } if (quoted) throw new ImportSourceError("unterminated quoted cell."); if (cell.length > 0 || record2.length > 0 || afterQuote) finishRecord(); return records; } function assertColumns(columns) { const seen = /* @__PURE__ */ new Set(); columns.forEach((column, index) => { if (column === "") throw new ImportSourceError(`CSV column ${index + 1} has an empty name.`); if (seen.has(column)) throw new ImportSourceError(`CSV column name "${column}" is duplicated.`); seen.add(column); }); } function decodeCsv(bytes, options) { const records = parseRfc4180(decodeImportText(bytes, options.encoding)); let columns; let rows; if (options.hasHeader) { columns = records[0] ?? []; rows = records.slice(1); } else { rows = records; columns = options.columns ? [...options.columns] : Array.from({ length: rows[0]?.length ?? 0 }, (_, i) => `c${i + 1}`); } assertColumns(columns); if (rows.length === 0) throw new ImportSourceError("CSV has no data rows."); rows.forEach((row, i) => { if (row.length !== columns.length) { throw new ImportSourceError(`CSV row ${i + (options.hasHeader ? 2 : 1)} has ${row.length} cells; expected ${columns.length}.`); } }); return { columns, rows }; } // src/import/convertImportCsvValue.ts init_define_KSQL_DOCS(); var LF_MULTI_TYPES = /* @__PURE__ */ new Set([ "CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT" ]); var USER_TYPES2 = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]); var ImportCsvValueError = class extends Error { constructor() { super("multiple-value CSV cell contains an empty LF-delimited item"); this.code = "ERR_IMPORT_MULTI_EMPTY_ITEM"; this.name = "ImportCsvValueError"; } }; function convertImportCsvValue(raw, type, options) { void options; if (!LF_MULTI_TYPES.has(type ?? "")) return raw; if (raw === "") return []; const items = raw.split(/\r\n|\n/); if (items.some((item) => item === "")) throw new ImportCsvValueError(); return USER_TYPES2.has(type ?? "") ? items.map((code) => ({ code })) : items; } // src/import/jsonMaterializer.ts init_define_KSQL_DOCS(); // src/import/jsonDecoder.ts init_define_KSQL_DOCS(); // src/import/jsonTokenizer.ts init_define_KSQL_DOCS(); function fail(message, offset, line, column) { throw new ImportSourceError(`JSON ${message} (offset=${offset}, line=${line}, column=${column}).`); } function decodeUtf8Json(bytes) { try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { throw new ImportSourceError("JSON source is not valid UTF-8."); } } function tokenizeJson(text) { const tokens = []; let i = 0, line = 1, column = 1; const advance = () => { const ch = text[i++]; if (ch === "\n") { line++; column = 1; } else column++; return ch; }; const position = () => ({ offset: i, line, column }); while (i < text.length) { const ch = text[i]; if (ch === " " || ch === " " || ch === "\r" || ch === "\n") { advance(); continue; } const start = position(); if ("{}[]:,".includes(ch)) { advance(); tokens.push({ kind: "punct", value: ch, ...start }); continue; } if (ch === '"') { advance(); let value = ""; let closed = false; while (i < text.length) { const c = advance(); if (c === '"') { closed = true; break; } if (c.charCodeAt(0) < 32) fail("string contains an unescaped control character", start.offset, start.line, start.column); if (c !== "\\") { value += c; continue; } if (i >= text.length) fail("string has an unterminated escape", start.offset, start.line, start.column); const esc2 = advance(); const simple = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: " " }; if (esc2 in simple) { value += simple[esc2]; continue; } if (esc2 !== "u") fail(`has invalid escape \\${esc2}`, i - 2, line, Math.max(1, column - 2)); const hex3 = text.slice(i, i + 4); if (!/^[0-9a-fA-F]{4}$/.test(hex3)) fail("has invalid unicode escape", i, line, column); for (let n = 0; n < 4; n++) advance(); const code = Number.parseInt(hex3, 16); if (code >= 55296 && code <= 56319) { if (text.slice(i, i + 2) !== "\\u" || !/^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) fail("has an unpaired high surrogate", i, line, column); advance(); advance(); const lowHex = text.slice(i, i + 4); for (let n = 0; n < 4; n++) advance(); const low = Number.parseInt(lowHex, 16); if (low < 56320 || low > 57343) fail("has an invalid surrogate pair", i - 4, line, Math.max(1, column - 4)); value += String.fromCodePoint(65536 + (code - 55296 << 10) + low - 56320); } else if (code >= 56320 && code <= 57343) { fail("has an unpaired low surrogate", i - 4, line, Math.max(1, column - 4)); } else value += String.fromCharCode(code); } if (!closed) fail("string is unterminated", start.offset, start.line, start.column); tokens.push({ kind: "string", value, ...start }); continue; } const rest = text.slice(i); const number4 = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(rest)?.[0]; if (number4) { for (let n = 0; n < number4.length; n++) advance(); tokens.push({ kind: "number", lexeme: number4, ...start }); continue; } const literal2 = /^(true|false|null)/.exec(rest)?.[0]; if (literal2) { for (let n = 0; n < literal2.length; n++) advance(); tokens.push({ kind: "literal", value: literal2 === "true" ? true : literal2 === "false" ? false : null, ...start }); continue; } fail(`has an unexpected token ${JSON.stringify(ch)}`, start.offset, start.line, start.column); } tokens.push({ kind: "eof", offset: i, line, column }); return tokens; } // src/import/jsonDecoder.ts function describe3(token) { return token.kind === "eof" ? "end of input" : token.kind === "punct" ? token.value : token.kind; } function decodeJsonRecords(bytes) { if (bytes.byteLength === 0) throw new ImportSourceError("JSON source is empty."); const tokens = tokenizeJson(decodeUtf8Json(bytes)); let index = 0; const fail3 = (message, token = tokens[index]) => { throw new ImportSourceError(`JSON ${message} (offset=${token.offset}, line=${token.line}, column=${token.column}).`); }; const isPunct = (token, value) => token.kind === "punct" && token.value === value; const punct = (value) => { const token = tokens[index]; if (token.kind !== "punct" || token.value !== value) fail3(`expected ${value}; found ${describe3(token)}`, token); index++; }; const parseValue = () => { const token = tokens[index++]; if (token.kind === "string") return token.value; if (token.kind === "number") return { kind: "number", lexeme: token.lexeme }; if (token.kind === "literal") return token.value; if (token.kind === "punct" && token.value === "{") { const object3 = /* @__PURE__ */ new Map(); if (isPunct(tokens[index], "}")) { index++; return object3; } while (true) { const key = tokens[index++]; if (key.kind !== "string") return fail3(`object key must be a string; found ${describe3(key)}`, key); const keyValue = key.value; if (object3.has(keyValue)) fail3(`duplicate key ${JSON.stringify(keyValue)}`, key); punct(":"); object3.set(keyValue, parseValue()); const separator = tokens[index]; if (isPunct(separator, "}")) { index++; break; } punct(","); } return object3; } if (token.kind === "punct" && token.value === "[") { const array2 = []; if (isPunct(tokens[index], "]")) { index++; return array2; } while (true) { array2.push(parseValue()); const separator = tokens[index]; if (isPunct(separator, "]")) { index++; break; } punct(","); } return array2; } return fail3(`expected a value; found ${describe3(token)}`, token); }; const root = parseValue(); if (tokens[index].kind !== "eof") fail3(`has trailing data; found ${describe3(tokens[index])}`); const records = root instanceof Map ? [root] : Array.isArray(root) ? root : fail3("root must be an object or array.", tokens[0]); if (records.length === 0) throw new ImportSourceError("JSON source contains no records."); records.forEach((record2, i) => { if (!(record2 instanceof Map)) throw new ImportSourceError(`JSON record ${i + 1} must be an object.`); }); return records; } // src/import/jsonMaterializer.ts var STRING_ARRAY_TYPES2 = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]); var CODE_ARRAY_TYPES2 = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]); function fail2(row, field, message) { throw new ImportSourceError(`JSON field validation failed (row=${row}, field=${field}): ${message}`); } function isNumber(value) { return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Map) && value.kind === "number"; } function materializeValue(value, target, row) { if (value === null) return ""; if (typeof value === "string") return value; if (typeof value === "boolean") fail2(row, target.code, "boolean is not accepted."); if (isNumber(value)) { if (target.fieldType === "NUMBER") fail2(row, target.code, "precision target requires a JSON string."); if (!/^-?(?:0|[1-9]\d*)$/.test(value.lexeme) || value.lexeme === "-0") { fail2(row, target.code, `JSON number ${value.lexeme} must be a non-negative-zero safe integer lexeme.`); } const number4 = Number(value.lexeme); if (!Number.isSafeInteger(number4)) fail2(row, target.code, `JSON number ${value.lexeme} is outside the safe integer range.`); return String(number4); } if (value instanceof Map) fail2(row, target.code, "object is not accepted for a flat field."); if (!Array.isArray(value)) fail2(row, target.code, "unsupported value type."); if (!STRING_ARRAY_TYPES2.has(target.fieldType) && !CODE_ARRAY_TYPES2.has(target.fieldType)) { fail2(row, target.code, "array is accepted only for multi-value fields."); } const strings = value.map((entry) => { if (typeof entry !== "string") fail2(row, target.code, "array elements must be strings."); return entry; }); if (new Set(strings).size !== strings.length) fail2(row, target.code, "array elements must not contain duplicates."); return CODE_ARRAY_TYPES2.has(target.fieldType) ? JSON.stringify(strings.map((code) => ({ code }))) : JSON.stringify(strings); } function materializeJsonDmlSource(_source, payload, targets, maxRows) { if (payload.encoding && payload.encoding !== "utf8") throw new ImportSourceError("JSON source is UTF-8 only."); const records = decodeJsonRecords(payload.bytes); if (records.length > maxRows) throw new ImportSourceError(`source rows (${records.length}) exceed maxRecords (${maxRows}).`); const targetByCode = new Map(targets.map((target) => [target.code, target])); if (targetByCode.size !== targets.length) throw new ImportSourceError("JSON target fields contain duplicates."); const rows = []; const importPresence = []; records.forEach((record2, index) => { for (const key of record2.keys()) { if (!targetByCode.has(key)) fail2(index + 1, key, "unknown key (not declared in INTO)."); } const row = {}; const present = /* @__PURE__ */ new Set(); for (const target of targets) { if (!record2.has(target.code)) continue; present.add(target.code); row[target.code] = materializeValue(record2.get(target.code), target, index + 1); } rows.push(row); importPresence.push(present); }); return { rows, columns: targets.map((target) => target.code), columnMeta: new Map(targets.map((target) => [target.code, { fieldType: target.fieldType }])), importPresence }; } // src/import/materializeDmlSource.ts function materializeCsvDmlSource(source, payload, maxRows, targetCodes, fieldInfos, recordNumberSourceHeader) { const decoded = decodeCsv(payload.bytes, { encoding: source.encoding ?? payload.encoding ?? "utf8", hasHeader: source.hasHeader, columns: source.columns }); if (decoded.rows.length > maxRows) { throw new ImportSourceError(`source rows (${decoded.rows.length}) exceed maxRecords (${maxRows}).`); } if (source.mappingMode === "BY_NAME") { if (!targetCodes || !fieldInfos) throw new Error("InternalError: BY NAME requires destination form metadata."); if (new Set(targetCodes).size !== targetCodes.length) { throw new ImportSourceError("ERR_IMPORT_HEADER_REUSED: a BY NAME header cannot be consumed more than once."); } const indexes = new Map(decoded.columns.map((column, index) => [column, index])); for (const code of targetCodes) { if (!indexes.has(code)) throw new ImportSourceError(`ERR_IMPORT_MISSING_COLUMN: required header "${code}" is missing.`); } const infoByCode = new Map(fieldInfos.map((info) => [info.code, info])); const targetSet = new Set(targetCodes); if (recordNumberSourceHeader && targetSet.has(recordNumberSourceHeader)) { throw new ImportSourceError("ERR_IMPORT_HEADER_REUSED: record-number source header is lookup-only and cannot be a write target."); } if (recordNumberSourceHeader && !indexes.has(recordNumberSourceHeader)) { throw new ImportSourceError(`ERR_IMPORT_MISSING_COLUMN: required header "${recordNumberSourceHeader}" is missing.`); } const ignoredKnownColumns = []; const ignoredUnknownColumns = []; const nonEmpty = (index) => decoded.rows.filter((row) => row[index] !== "").length; const reasonFor = (info) => { if (info.fieldType === "FILE") return "FILE attachment is outside flat IMPORT scope"; if (info.inSubtable || info.fieldType === "SUBTABLE") return "subtable field is not writable in Phase 3"; if (info.writable === false) return `non-writable ${info.fieldType} field`; return `known export-only ${info.fieldType} field`; }; for (const [index, column] of decoded.columns.entries()) { if (targetSet.has(column) || column === recordNumberSourceHeader) continue; const info = infoByCode.get(column); if (info) ignoredKnownColumns.push({ column, reason: reasonFor(info), nonEmptyCells: nonEmpty(index) }); else if (!source.ignoreUnknownColumns) throw new ImportSourceError(`ERR_IMPORT_UNKNOWN_COLUMN: unknown CSV header "${column}".`); else ignoredUnknownColumns.push({ column, reason: "unknown column ignored by explicit policy", nonEmptyCells: nonEmpty(index) }); } for (const code of targetCodes) { const info = infoByCode.get(code); if (!info) throw new Error(`ArgumentError: DML target field ${code} does not exist.`); if (info.inSubtable || info.writable === false || info.fieldType === "FILE" || info.fieldType === "SUBTABLE") { throw new Error(`ArgumentError: DML target field ${code} is not writable (${info.fieldType}).`); } } const importRowErrors = []; const rows2 = decoded.rows.map((values) => { const errors = []; const row = {}; for (const code of targetCodes) { const raw = values[indexes.get(code)]; try { row[code] = convertImportCsvValue(raw, infoByCode.get(code)?.fieldType, { cliKintone: true }); } catch (error51) { if (!(error51 instanceof ImportCsvValueError)) throw error51; row[code] = raw; errors.push({ field: code, code: error51.code, message: error51.message }); } } importRowErrors.push(errors); return row; }); return { rows: rows2, columns: [...targetCodes], columnMeta: new Map(targetCodes.map((code) => [code, { fieldType: infoByCode.get(code)?.fieldType ?? "SINGLE_LINE_TEXT" }])), importRowErrors, ...recordNumberSourceHeader ? { recordNumberSourceValues: decoded.rows.map((row) => row[indexes.get(recordNumberSourceHeader)]) } : {}, importAudit: { mapping: "BY_NAME", writtenColumns: [...targetCodes], ignoredKnownColumns, ignoredUnknownColumns } }; } const rows = decoded.rows.map((values) => Object.fromEntries(decoded.columns.map((column, i) => [column, values[i]]))); return { rows, columns: decoded.columns, // CSV cells are decoded as strings; projections such as CAST may replace this metadata downstream. columnMeta: new Map(decoded.columns.map((column) => [column, { fieldType: "SINGLE_LINE_TEXT" }])) }; } // src/import/importRecordsMaterializer.ts init_define_KSQL_DOCS(); var sourceFail = (parentRow, code, message) => { throw new ImportSourceError(`JSON subtable validation failed (parentRow=${parentRow}, field=${code}): ${message}`); }; function materializeJsonImportRecords(_source, payload, targets, maxParents, maxChildRows = maxParents) { if (payload.encoding && payload.encoding !== "utf8") throw new ImportSourceError("JSON source is UTF-8 only."); const decoded = decodeJsonRecords(payload.bytes); if (decoded.length > maxParents) throw new ImportSourceError(`source parent rows (${decoded.length}) exceed maxRecords (${maxParents}).`); const targetByCode = new Map(targets.map((target) => [target.kind === "FIELD" ? target.field : target.subtableCode, target])); if (targetByCode.size !== targets.length) throw new ImportSourceError("IMPORT targets contain duplicates."); let childTotal = 0; return { records: decoded.map((record2, index) => { const parentRow = index + 1; for (const code of record2.keys()) if (!targetByCode.has(code)) sourceFail(parentRow, code, "unknown key (not declared in INTO)."); const top = /* @__PURE__ */ new Map(); const subtables = /* @__PURE__ */ new Map(); const replacementTables = /* @__PURE__ */ new Set(); for (const target of targets) { const code = target.kind === "FIELD" ? target.field : target.subtableCode; if (!record2.has(code)) continue; const value = record2.get(code); if (target.kind === "FIELD") { if (value instanceof Map) sourceFail(parentRow, code, "object is not accepted for a top-level field."); top.set(code, value); continue; } if (!Array.isArray(value)) sourceFail(parentRow, code, "subtable value must be an array."); replacementTables.add(code); const children = new Set(target.children); const rows = value.map((entry, childIndex) => { if (!(entry instanceof Map)) sourceFail(parentRow, code, `childRow=${childIndex + 1} must be an object.`); const child = entry; for (const childCode of child.keys()) { if (!children.has(childCode)) sourceFail(parentRow, childCode, `unknown child key in subtable ${code} at childRow=${childIndex + 1}.`); } childTotal++; if (childTotal > maxChildRows) throw new ImportSourceError(`source child rows (${childTotal}) exceed limit (${maxChildRows}).`); return { childRowNumber: childIndex + 1, values: child }; }); subtables.set(code, rows); } return { rowNumber: parentRow, top, subtables, replacementTables }; }) }; } function materializeCliKintoneCsvImportRecords(source, payload, targets, replacementTables, maxParents, recordNumberSourceHeader) { const decoded = decodeCsv(payload.bytes, { encoding: source.encoding ?? payload.encoding ?? "utf8", hasHeader: source.hasHeader, columns: source.columns }); if (!source.hasHeader || decoded.columns[0] !== "*") throw new ImportSourceError('ERR_IMPORT_MARKER: first CSV header must be "*".'); const indexes = new Map(decoded.columns.map((code, index) => [code, index])); if (recordNumberSourceHeader && !indexes.has(recordNumberSourceHeader)) throw new ImportSourceError(`ERR_IMPORT_MISSING_COLUMN: required header "${recordNumberSourceHeader}" is missing.`); const fields = targets.filter((target) => target.kind === "FIELD"); const tables = targets.filter((target) => target.kind === "SUBTABLE"); for (const field of fields) if (!indexes.has(field.field)) throw new ImportSourceError(`ERR_IMPORT_MISSING_COLUMN: required header "${field.field}" is missing.`); for (const table of tables) { if (!table.rowIdSourceHeader || !indexes.has(table.rowIdSourceHeader)) throw new ImportSourceError(`ERR_IMPORT_MISSING_COLUMN: row-ID header for ${table.subtableCode} is missing.`); for (const child of table.children) if (!indexes.has(child)) throw new ImportSourceError(`ERR_IMPORT_MISSING_COLUMN: required child header "${child}" is missing.`); } const records = []; let current; decoded.rows.forEach((cells, physicalIndex) => { const sourceRowNumber = physicalIndex + 2; const marker = cells[0]; if (marker !== "" && marker !== "*") throw new ImportSourceError(`ERR_IMPORT_MARKER: invalid marker ${JSON.stringify(marker)} at source row ${sourceRowNumber}.`); if (marker === "*") { if (records.length >= maxParents) throw new ImportSourceError(`source parent rows exceed maxRecords (${maxParents}).`); current = { rowNumber: records.length + 1, markerRowNumber: sourceRowNumber, top: new Map(fields.map((field) => [field.field, cells[indexes.get(field.field)]])), subtables: new Map(tables.map((table) => [table.subtableCode, []])), replacementTables: new Set(replacementTables), ...recordNumberSourceHeader ? { recordNumberSourceValue: cells[indexes.get(recordNumberSourceHeader)] } : {} }; records.push(current); } else if (!current) { throw new ImportSourceError(`ERR_IMPORT_MARKER: first data row must start a parent (source row ${sourceRowNumber}).`); } else { for (const field of fields) { const continuationValue = cells[indexes.get(field.field)]; if (continuationValue !== "" && continuationValue !== current.top.get(field.field)) { throw new ImportSourceError(`ERR_IMPORT_PARENT_VALUE_ON_CONTINUATION: ${field.field} at source row ${sourceRowNumber}.`); } } if (recordNumberSourceHeader) { const continuationValue = cells[indexes.get(recordNumberSourceHeader)]; if (continuationValue !== "" && continuationValue !== current.recordNumberSourceValue) { throw new ImportSourceError(`ERR_IMPORT_PARENT_VALUE_ON_CONTINUATION: ${recordNumberSourceHeader} at source row ${sourceRowNumber}.`); } } } for (const table of tables) { const rowId = cells[indexes.get(table.rowIdSourceHeader)]; const values = new Map(table.children.map((child) => [child, cells[indexes.get(child)]])); if (rowId === "" && [...values.values()].every((value) => value === "")) continue; const rows = current.subtables.get(table.subtableCode); rows.push({ childRowNumber: rows.length + 1, sourceRowNumber, ...rowId ? { rowId } : {}, values }); } }); if (records.length === 0) throw new ImportSourceError("CSV has no parent rows."); return { records }; } // src/import/importRecordValidation.ts init_define_KSQL_DOCS(); var USER_TYPES3 = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]); var UNSUPPORTED_CHILD_TYPES = /* @__PURE__ */ new Set(["SUBTABLE", "FILE", "CALC", "RECORD_NUMBER", "CREATOR", "CREATED_TIME", "MODIFIER", "UPDATED_TIME", "STATUS", "STATUS_ASSIGNEE", "CATEGORY", "REFERENCE_TABLE"]); function assertImportRejectLimit(prepared, rejectLimit) { if (rejectLimit != null && prepared.invalidParentRows.size > rejectLimit) { throw new Error(`RejectLimitExceededError: rejected parents (${prepared.invalidParentRows.size}) exceed REJECT LIMIT (${rejectLimit}).`); } } function prepareImportRecords(materialized, targets, fieldInfos, numberPrecision, operation) { const topInfos = new Map(fieldInfos.filter((f) => !f.inSubtable).map((f) => [f.code, f])); const scoped = /* @__PURE__ */ new Map(); for (const info of fieldInfos) if (info.inSubtable && info.subtableCode) { let children = scoped.get(info.subtableCode); if (!children) scoped.set(info.subtableCode, children = /* @__PURE__ */ new Map()); children.set(info.code, info); } const targetTop = targets.filter((t) => t.kind === "FIELD"); const targetTables = targets.filter((t) => t.kind === "SUBTABLE"); for (const target of targetTop) assertWritable2(target.field, topInfos.get(target.field), void 0); for (const target of targetTables) { const table = topInfos.get(target.subtableCode); if (!table || table.fieldType !== "SUBTABLE") throw new Error(`ArgumentError: IMPORT subtable ${target.subtableCode} does not exist.`); const children = scoped.get(target.subtableCode) ?? /* @__PURE__ */ new Map(); for (const child of target.children) assertWritable2(child, children.get(child), target.subtableCode); } const tableCounts = new Map(targetTables.map((t) => [t.subtableCode, { parentsPresent: 0, childRows: 0, validChildRows: 0, invalidChildRows: 0 }])); const parents = materialized.records.map((record2) => validateParent(record2, targetTop, targetTables, topInfos, scoped, numberPrecision, operation, tableCounts)); const errors = parents.flatMap((parent) => [...parent.errors]); return { parents, errors, invalidParentRows: new Set(parents.filter((p) => !p.valid).map((p) => p.parentRow)), tableCounts }; } function validateParent(source, topTargets, tableTargets, topInfos, scoped, precision, operation, tableCounts) { const errors = []; const top = {}; for (const target of topTargets) { if (!source.top.has(target.field)) continue; validateValue(source.top.get(target.field), topInfos.get(target.field), precision, top, target.field, errors, location(source, operation, target.field)); } const createValidationOnly = {}; if (operation === "INSERT") for (const info of topInfos.values()) { if (info.fieldType === "SUBTABLE" || info.writable === false || source.top.has(info.code)) continue; validateMissing(info, precision, createValidationOnly, errors, location(source, operation, info.code)); } const subtables = /* @__PURE__ */ new Map(); for (const target of tableTargets) { if (!source.subtables.has(target.subtableCode)) continue; const count = tableCounts.get(target.subtableCode); count.parentsPresent++; const preparedRows = []; for (const child of source.subtables.get(target.subtableCode)) { count.childRows++; const before = errors.length; const record2 = {}; const infos = scoped.get(target.subtableCode); for (const code of target.children) { const info = infos.get(code); const loc = location(source, operation, code, target.subtableCode, child.childRowNumber, child.sourceRowNumber ?? source.markerRowNumber); if (child.values.has(code)) validateValue(child.values.get(code), info, precision, record2, code, errors, loc); else validateMissing(info, precision, record2, errors, loc); } if (errors.length === before) { count.validChildRows++; preparedRows.push(record2); } else count.invalidChildRows++; } subtables.set(target.subtableCode, preparedRows); } return { parentRow: source.rowNumber, valid: errors.length === 0, top, subtables, replacementTables: source.replacementTables, errors }; } function assertWritable2(code, info, table) { if (!info) throw new Error(table ? `ArgumentError: IMPORT child ${code} does not belong to subtable ${table}.` : `ArgumentError: IMPORT top-level field ${code} does not exist.`); if (info.writable === false || table && UNSUPPORTED_CHILD_TYPES.has(info.fieldType)) { throw new Error(`ArgumentError: IMPORT ${table ? `child ${table}.${code}` : `field ${code}`} is not writable (${info.fieldType}).`); } } function validateMissing(info, precision, record2, errors, loc) { const raw = isEmptyDmlValue(info.defaultValue) ? "" : info.defaultValue; validateValue(raw, info, precision, record2, info.code, errors, loc, !isEmptyDmlValue(info.defaultValue)); } function validateValue(raw, info, precision, record2, code, errors, loc, isDefault = false) { const normalizedRaw = decodeRaw(raw); const result = validateAndNormalizeDmlValue(normalizedRaw, info, precision); if (!result.ok) errors.push({ ...loc, code: result.code, message: isDefault ? `\u65E2\u5B9A\u5024: ${result.message}` : result.message }); else record2[code] = { value: preserveUserCodes(normalizedRaw, info) ? normalizedRaw : result.value }; } function decodeRaw(raw) { if (isJsonNumber(raw)) return raw.lexeme; if (Array.isArray(raw)) return raw.map((value) => value instanceof Map ? value : isJsonNumber(value) ? value.lexeme : value); return raw; } function isJsonNumber(raw) { return typeof raw === "object" && raw !== null && raw.kind === "number"; } function preserveUserCodes(raw, info) { return USER_TYPES3.has(info.fieldType) && Array.isArray(raw) && raw.every((v) => typeof v === "object" && v !== null && "code" in v); } function location(source, operation, field, subtable, subrow, sourceRow) { const physicalRow = sourceRow ?? source.markerRowNumber; return { operation, parentRow: source.rowNumber, field, ...subtable ? { subtable } : {}, ...subrow == null ? {} : { subrow }, ...physicalRow == null ? {} : { sourceRow: physicalRow }, sourceValues: subtable ? source.subtables.get(subtable)?.[subrow - 1]?.values ?? /* @__PURE__ */ new Map() : source.top }; } // src/import/importErrors.ts init_define_KSQL_DOCS(); var IMPORT_VALIDATION_META_COLUMNS = [ "$err_statement", "$err_operation", "$err_row", "$err_field", "$err_subtable", "$err_subrow", "$err_source_row", "$err_code", "$err_message" ]; function materializeImportValidationErrors(errors, payloadFields, statementNumber = 1) { return errors.map((error51) => { const row = {}; for (const field of payloadFields) row[field] = error51.sourceValues.get(field) == null ? "" : render(error51.sourceValues.get(field)); row["$err_statement"] = String(statementNumber); row["$err_operation"] = error51.operation; row["$err_row"] = String(error51.parentRow); row["$err_field"] = error51.field; row["$err_subtable"] = error51.subtable ?? ""; row["$err_subrow"] = error51.subrow == null ? "" : String(error51.subrow); row["$err_source_row"] = error51.sourceRow == null ? null : String(error51.sourceRow); row["$err_code"] = error51.code; row["$err_message"] = error51.message; return row; }); } function render(value) { if (value === null || value === void 0) return ""; if (typeof value === "object" && value !== null && "kind" in value && "lexeme" in value && value.kind === "number") { return String(value.lexeme); } if (Array.isArray(value)) return JSON.stringify(value); return String(value); } // src/import/subtablePayload.ts init_define_KSQL_DOCS(); function buildImportRecordPayload(top, subtables, rowIdMode) { const record2 = {}; for (const [code, value] of top) record2[code] = { value }; for (const [tableCode, sourceRows] of subtables) { record2[tableCode] = { value: sourceRows.map((sourceRow) => ({ ...rowIdMode === "PRESERVE" && sourceRow.rowId ? { id: sourceRow.rowId } : {}, value: Object.fromEntries([...sourceRow.values].map(([childCode, value]) => [childCode, { value }])) })) }; } return record2; } function buildJsonImportRecordPayload(top, subtables) { return buildImportRecordPayload(top, subtables, "DROP"); } // src/import/jsonSubtableWritePlan.ts init_define_KSQL_DOCS(); function assertJsonImportHasNoRowIds(materialized) { for (const parent of materialized.records) for (const [table, rows] of parent.subtables) { for (const row of rows) { if (row.rowId !== void 0 || row.values.has("_rid") || row.values.has("id")) { throw new Error(`ArgumentError: JSON IMPORT subtable ${table} does not accept _rid/id; rows are always newly numbered.`); } } } } function buildJsonSubtableWritePlan(parents, targetIds, existingById) { return parents.map((parent, index) => { const targetId = targetIds[index]; const existing = targetId === void 0 ? void 0 : existingById.get(targetId); if (targetId !== void 0 && !existing) throw new Error(`InternalError: IMPORT UPSERT target APP record ${targetId} was not loaded.`); const tables = [...parent.subtables].map(([table, input]) => { const raw = existing?.record[table]?.value; const existingRows = Array.isArray(raw) ? raw.length : 0; return { table, existingRows, inputRows: input.length, addRows: input.length, deleteRows: existingRows }; }); return { parentRow: parent.parentRow, mode: targetId === void 0 ? "INSERT" : "UPDATE", ...targetId === void 0 ? {} : { targetId, revision: existing?.revision }, top: parent.top, subtables: parent.subtables, tables }; }); } // src/import/subtableReplacementPlan.ts init_define_KSQL_DOCS(); function tableRows(record2, table) { const raw = record2[table]?.value; return Array.isArray(raw) ? raw : []; } function assertNoDuplicateCsvSubtableRowIds(records) { const seen = /* @__PURE__ */ new Map(); for (const parent of records) for (const [table, rows] of parent.subtables) for (const row of rows) { if (!row.rowId) continue; const key = `${table}\0${row.rowId}`; if (seen.has(key)) throw new Error(`ERR_SUBTABLE_ROW_ID_DUP_SOURCE: duplicate row ID ${row.rowId} in ${table}`); seen.set(key, parent.rowNumber); } } function buildCsvSubtableReplacementPlan(sources, prepared, targetIds, existingById, ownership) { return prepared.map((parent, index) => { const source = sources[index]; const targetId = targetIds[index]; const existing = targetId === void 0 ? void 0 : existingById.get(targetId); const errors = [...parent.errors]; if (!existing || targetId === void 0) return { parentRow: parent.parentRow, targetId: targetId ?? 0, valid: false, top: parent.top, subtables: /* @__PURE__ */ new Map(), tables: [], errors }; const subtables = /* @__PURE__ */ new Map(); const tables = []; for (const table of parent.replacementTables) { const current = tableRows(existing.record, table); const currentIds = new Set(current.map((row) => row.id).filter((id) => !!id)); const input = source.subtables.get(table) ?? []; const normalized = parent.subtables.get(table) ?? []; let updateRows = 0, addRows = 0, rowIdNotFound = 0; const payloadRows = input.map((row, rowIndex) => { const normalizedRecord = normalized[rowIndex] ?? {}; if (row.rowId && currentIds.has(row.rowId)) { updateRows++; return { rowId: row.rowId, record: normalizedRecord }; } if (row.rowId) { const owners = ownership.get(row.rowId) ?? []; if (owners.some((owner) => owner.parentId !== targetId || owner.table !== table)) errors.push({ operation: "UPDATE", parentRow: parent.parentRow, field: row.rowId, subtable: table, subrow: row.childRowNumber, sourceRow: row.sourceRowNumber, code: "ERR_IMPORT_FIELD_OWNERSHIP", message: `rowIdOwnedElsewhere: ${row.rowId}`, sourceValues: row.values }); rowIdNotFound++; } addRows++; return { record: normalizedRecord }; }); subtables.set(table, payloadRows); tables.push({ table, existingRows: current.length, inputRows: input.length, updateRows, addRows, deleteRows: current.length - updateRows, rowIdNotFound }); } return { parentRow: parent.parentRow, targetId, ...existing.revision === void 0 ? {} : { revision: existing.revision }, valid: errors.length === 0, top: parent.top, subtables, tables, errors }; }); } // src/import/importProjection.ts init_define_KSQL_DOCS(); var IMPORT_PROJECTION_SOURCE = "#__import_source"; function bindImportProjection(projection) { return { ...projection, from: { appId: 0, alias: null, cteName: IMPORT_PROJECTION_SOURCE } }; } // src/import/recordNumberUpdate.ts init_define_KSQL_DOCS(); function normalizeImportRecordNumber(raw) { return /^[0-9]+$/.test(raw) ? raw.replace(/^0+(?=\d)/, "") : null; } function preflightImportRecordNumbers(values, header) { const normalized = values.map(normalizeImportRecordNumber); const seen = /* @__PURE__ */ new Set(); for (const key of normalized) { if (key === null) continue; if (seen.has(key)) { throw new Error("ERR_RECORD_NUMBER_DUP_SOURCE: source contains a duplicate record number"); } seen.add(key); } return { normalized, errors: normalized.map((key) => key === null ? [{ field: header, code: "ERR_RECORD_NUMBER_INVALID", message: `${header} must be a non-empty ASCII decimal record number` }] : []) }; } // src/execute.ts var SEARCH_ABORTED_WARNING = "\u691C\u7D22\u304C 10 \u4E07\u4EF6\u3067\u6253\u3061\u5207\u3089\u308C\u3001\u7D50\u679C\u304C\u6B20\u843D\u3057\u305F\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002"; var SearchAbortedError = class extends Error { constructor() { super("SearchAbortedError: kintone \u306E\u691C\u7D22\u304C 10 \u4E07\u4EF6\u3067\u6253\u3061\u5207\u3089\u308C\u305F\u305F\u3081\u3001\u5B8C\u5168\u306A\u5BFE\u8C61\u96C6\u5408\u3092\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002"); this.name = "SearchAbortedError"; } }; var materializedMetaBySelectResult = /* @__PURE__ */ new WeakMap(); var materializedMetaByValidationResult = /* @__PURE__ */ new WeakMap(); var importSourceByDmlStatement = /* @__PURE__ */ new WeakMap(); var defaultCacheContextByClient = /* @__PURE__ */ new WeakMap(); var nextDefaultCacheContextId = 1; function resolveCacheContext(client, explicit) { if (explicit) return explicit; let context = defaultCacheContextByClient.get(client); if (!context) { context = `client:${nextDefaultCacheContextId++}`; defaultCacheContextByClient.set(client, context); } return context; } async function execute(sql, client, options = {}) { const startedAt = Date.now(); const cacheContext = resolveCacheContext(client, options.cacheContext); const stmt = parseSql(sql, options.enableImport === true); const metrics = createEmptyMetrics(); const countedClient = wrapClientWithMetrics(client, metrics); const collector = { aborted: false }; const guardedClient = wrapClientWithSearchAbort( countedClient, collector, !isSelectLikeStatement(stmt) ); const result = await executeParsedStatement( stmt, guardedClient, options, cacheContext ); metrics.elapsedMs = Date.now() - startedAt; return { ...attachSearchAbortWarning(result, collector), metrics }; } function createEmptyMetrics() { return { getCalls: 0, postCalls: 0, putCalls: 0, deleteCalls: 0, fieldCalls: 0, numberPrecisionCalls: 0, appsCalls: 0, processStatusCalls: 0, cursorCreateCalls: 0, cursorGetCalls: 0, cursorDeleteCalls: 0, cursorRecordsScanned: 0, cursorActiveCurrent: 0, cursorActivePeak: 0, cursorCleanupFailures: 0, cursorCreateOutcomeUnknown: 0, cursorQuarantinedCurrent: 0, fetchedRows: 0, elapsedMs: 0 }; } function wrapClientWithMetrics(client, metrics) { return { getRecords: async (params) => { metrics.getCalls += 1; const res = await client.getRecords(params); metrics.fetchedRows += res.records.length; return res; }, openCursor: async (params) => { metrics.cursorCreateCalls += 1; let handle; try { handle = await client.openCursor(params); } catch (error51) { if (error51 instanceof Error && error51.name === "CursorCreateOutcomeUnknownError") { metrics.cursorCreateOutcomeUnknown += 1; metrics.cursorQuarantinedCurrent += 1; } throw error51; } metrics.cursorActiveCurrent += 1; metrics.cursorActivePeak = Math.max(metrics.cursorActivePeak, metrics.cursorActiveCurrent); let released = false; const markReleased = () => { if (released) return; released = true; metrics.cursorActiveCurrent -= 1; }; return { totalCount: handle.totalCount, nextPage: async () => { metrics.cursorGetCalls += 1; const page = await handle.nextPage(); metrics.cursorRecordsScanned += page.records.length; if (!page.next) markReleased(); return page; }, close: async () => { if (!released) metrics.cursorDeleteCalls += 1; try { await handle.close(); markReleased(); } catch (error51) { metrics.cursorCleanupFailures += 1; metrics.cursorQuarantinedCurrent += 1; throw error51; } } }; }, postRecords: (params) => { metrics.postCalls += 1; return client.postRecords(params); }, putRecords: (params) => { metrics.putCalls += 1; return client.putRecords(params); }, deleteRecords: (params) => { metrics.deleteCalls += 1; return client.deleteRecords(params); }, getApps: () => { metrics.appsCalls += 1; return client.getApps(); }, getFields: (appId) => { metrics.fieldCalls += 1; return client.getFields(appId); }, getNumberPrecision: (appId) => { metrics.numberPrecisionCalls += 1; return client.getNumberPrecision(appId); }, getProcessStatuses: (appId) => { metrics.processStatusCalls += 1; return client.getProcessStatuses(appId); } }; } function wrapClientWithSearchAbort(client, collector, failClosed) { return { ...client, getRecords: async (params) => { const response = await client.getRecords(params); if (response.searchAborted) { collector.aborted = true; if (failClosed) throw new SearchAbortedError(); } return response; } }; } function wrapClientWithCursorScope(client) { const active = /* @__PURE__ */ new Set(); return { client: { ...client, openCursor: async (params) => { const handle = await client.openCursor(params); active.add(handle); const remove = () => active.delete(handle); return { totalCount: handle.totalCount, async nextPage() { const page = await handle.nextPage(); if (!page.next) remove(); return page; }, async close() { try { await handle.close(); } finally { remove(); } } }; } }, closeActive: async () => { await Promise.all([...active].map((handle) => handle.close().catch(() => void 0))); } }; } function isSelectLikeStatement(stmt) { return stmt.type === "SELECT" || stmt.type === "UNION" || stmt.type === "WITH"; } function attachSearchAbortWarning(result, collector) { if (!collector.aborted || result.type !== "SELECT") return result; const warnings = new Set(result.warnings ?? []); warnings.add(SEARCH_ABORTED_WARNING); return { ...result, warnings: [...warnings] }; } async function executeParsedStatement(stmt, client, options, cacheContext) { const unresolved = findVariableRef(stmt); if (unresolved !== null && !isApplyParentKlikeStatement(stmt)) { throw new Error(`ParseError: variable @${unresolved} is not defined in a batch.`); } assertApplyScope("phase15b", stmt); assertApplyExecutionScope("phase15b", stmt); validateKlikeStatement(stmt); if (stmt.type === "IMPORT") return executeImport(stmt, client, options, cacheContext); if (stmt.type === "UPDATE" && stmt.applyBlocks?.length) { if (stmt.validationErrorTable) { throw new Error("ArgumentError: VALIDATE ONLY INTO requires a batch."); } return executeUpdate(stmt, client, options, cacheContext); } if ("validateOnly" in stmt && stmt.validateOnly === true) { if (stmt.validationErrorTable) { throw new Error("ArgumentError: VALIDATE ONLY INTO requires a batch."); } return executeDmlValidation(stmt, client, { ...options, onLimitReached: "error" }, cacheContext, void 0, 1); } if ("onErrorSkip" in stmt && stmt.onErrorSkip === true) { throw new Error("ArgumentError: ON ERROR SKIP requires a batch."); } switch (stmt.type) { case "VALIDATE": return executeExistingRecordValidation(stmt, client, options, cacheContext); case "SELECT": return executeSelect(stmt, client, options, cacheContext); case "UNION": return executeUnion(stmt, client, options, cacheContext); case "WITH": return executeWith(stmt, client, options, cacheContext); case "INSERT": return executeInsert(stmt, client, options, cacheContext); case "INSERT_SELECT": return executeInsertSelect(stmt, client, options, cacheContext); case "UPSERT": return executeUpsert(stmt, client, options, cacheContext); case "UPSERT_SELECT": return executeUpsertSelect(stmt, client, options, cacheContext); case "UPDATE": return executeUpdate(stmt, client, options, cacheContext); case "DELETE": return executeDelete(stmt, client, options, cacheContext); case "REORDER": return executeReorder(stmt, client, options, cacheContext); case "SHOW_APPS": return executeShowApps(client); case "DESCRIBE": return executeDescribe(stmt, client, cacheContext); case "EXPLAIN": return executeExplain( stmt, client, cacheContext, options.maxRecords ?? 1e4, options.cursorMaxActive ?? 2, stmt.query.type === "UPDATE" && stmt.query.applyBlocks?.length ? resolveApplyGuardLimit(options.dmlMaxRows, "dmlMaxRows", DEFAULT_APPLY_MAX_ROWS) : DEFAULT_APPLY_MAX_ROWS, stmt.query.type === "UPDATE" && stmt.query.applyBlocks?.length ? resolveApplyGuardLimit(options.dmlMaxSubtableRows, "dmlMaxSubtableRows", DEFAULT_APPLY_MAX_SUBTABLE_ROWS) : DEFAULT_APPLY_MAX_SUBTABLE_ROWS ); // 一時テーブルはバッチスコープのため単文実行では拒否する(executeBatch を使う) case "CREATE_TEMP_TABLE": throw new Error("ArgumentError: CREATE TEMP TABLE requires a batch (temp tables are batch-scoped)."); case "DROP_TEMP_TABLE": throw new Error("ArgumentError: DROP TEMP TABLE requires a batch (temp tables are batch-scoped)."); case "SET_VARIABLE": throw new Error("ArgumentError: SET variable requires a batch."); case "DECLARE_VARIABLE": throw new Error("ArgumentError: DECLARE variable requires a batch."); case "ASSERT": return executeAssert(stmt, client, options, cacheContext); } } var EXISTING_VALIDATION_COLUMNS = [ "$id", "$err_field", "$err_code", "$err_message", "$err_value", "$err_subtable", "$err_subrow", "$err_subrow_id", "$err_count" ]; var EXISTING_VALIDATION_SUMMARY_COLUMNS = [ "$id", "$err_subtable", "$err_field", "$err_code", "$err_count" ]; function collectValidateWhereFields(where) { const fields = []; const seen = /* @__PURE__ */ new Set(); const add = (field) => { if (!seen.has(field)) { seen.add(field); fields.push(field); } }; const visit = (node) => { if (Array.isArray(node)) { node.forEach(visit); return; } if (node === null || typeof node !== "object") return; const obj = node; if (obj.type === "FIELD" && typeof obj.field === "string") add(obj.field); if (obj.type === "FIELD_REF" && typeof obj.field === "string") add(obj.field); Object.values(obj).forEach(visit); }; visit(where); return fields; } function existingValidationColumnMeta(summary = false) { const columns = summary ? EXISTING_VALIDATION_SUMMARY_COLUMNS : EXISTING_VALIDATION_COLUMNS; return new Map(columns.map((column) => [column, { fieldType: column === "$id" || column === "$err_count" ? "KSQL_NUMBER" : "KSQL_STRING", sortKind: column === "$id" || column === "$err_count" ? "number" : "string", semantics: syntheticSemantics(column === "$id" || column === "$err_count" ? "number" : "string") }])); } async function executeExistingRecordValidation(stmt, client, options, cacheContext) { if (stmt.errorTable) throw new Error("ArgumentError: VALIDATE INTO requires a batch."); return executeExistingRecordValidationCore(stmt, client, options, cacheContext); } async function executeExistingRecordValidationCore(stmt, client, options, cacheContext) { const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext); const infoByCode = new Map(fieldInfos.filter((field) => !field.inSubtable).map((field) => [field.code, field])); const childCodes = new Set(fieldInfos.filter((field) => field.inSubtable).map((field) => field.code)); const targets = resolveExistingValidationTargets(stmt, fieldInfos); const checkGroups = stmt.checkGroups ?? []; const checkRefs2 = collectCheckFieldRefs(checkGroups); for (const ref of checkRefs2) { if (ref.field !== "$id" && !infoByCode.has(ref.field) && !childCodes.has(ref.field)) { throw customCheckParseError(`CHECK \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F APP${stmt.appId} \u306B\u5B58\u5728\u3057\u307E\u305B\u3093`); } if (ref.field !== "$id" && !infoByCode.has(ref.field) && childCodes.has(ref.field)) { throw new Error(`ArgumentError: VALIDATE \u306E CHECK \u3067\u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\u3002`); } } const evaluationTypes = new Map([...infoByCode].map(([code, field]) => [code, field.fieldType])); evaluationTypes.set("$id", "RECORD_NUMBER"); assertCheckComparisonTypes(stmt, evaluationTypes); const whereFields = collectValidateWhereFields(stmt.where); const requiredFields = [.../* @__PURE__ */ new Set([ "$id", ...targets.map((target) => target.subtableCode ?? target.field.code), ...whereFields, ...checkRefs2.map((ref) => ref.field) ])]; for (const field of whereFields) { if (field !== "$id" && !infoByCode.has(field) && !childCodes.has(field)) { throw new Error(`ArgumentError: WHERE field ${field} does not exist in APP${stmt.appId}.`); } if (field !== "$id" && !infoByCode.has(field) && childCodes.has(field)) { throw new Error(`ArgumentError: VALIDATE \u306E WHERE \u3067\u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${field} \u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\u3002`); } } const numberPrecision = targets.some((target) => target.field.fieldType === "NUMBER") ? await getNumberPrecisionCached(stmt.appId, client, cacheContext) : void 0; const semantics = (field) => field.field === "$id" ? resolveFieldSemantics({ fieldType: "__ID__" }) : infoByCode.get(field.field)?.semantics ?? (infoByCode.has(field.field) ? resolveFieldSemantics(infoByCode.get(field.field)) : void 0); const capability = classifyWhereCapability(stmt.where, semantics); if (capability.capability === "UNSUPPORTED") { throw new Error(`ArgumentError: WHERE predicate is unsupported (${formatWhereCapabilityFailure(capability)}).`); } const fieldTypes = new Map([...infoByCode].map(([code, field]) => [code, field.fieldType])); const fieldOptions = new Map([...infoByCode.values()].flatMap((field) => field.optionOrder ? [[field.code, new Set(Object.keys(field.optionOrder))]] : [])); const prefilter = stmt.where === null ? null : capability.capability === "EXACT_PUSHDOWN" ? stmt.where : extractSafePushdownLeaves(stmt.where, { allowUnqualifiedFields: true, fieldTypes, fieldOptions, allowKlike: false }); const query = prefilter === null ? "" : whereToKintone(prefilter); const records = await fetchAll(client.getRecords, stmt.appId, query, requiredFields, { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" }); const validationRows = records.map((record2) => ({ id: String(record2["$id"]?.value ?? ""), record: record2, flat: flatten(record2, null) })).filter((row) => stmt.where === null || evalWhere(stmt.where, row.flat, (field) => evaluationTypes.get(field.field))); const rows = []; const detailRows = /* @__PURE__ */ new Map(); const summaryRows = /* @__PURE__ */ new Map(); const errorRecordIds = /* @__PURE__ */ new Set(); let errorCount = 0; const appendError = (error51) => { errorRecordIds.add(error51.id); errorCount += 1; if (stmt.summary) { const key2 = JSON.stringify([error51.id, error51.subtable ?? "", error51.field, error51.code]); const current2 = summaryRows.get(key2); if (current2) current2["$err_count"] = String(Number(current2["$err_count"]) + 1); else summaryRows.set(key2, { "$id": error51.id, "$err_subtable": error51.subtable ?? "", "$err_field": error51.field, "$err_code": error51.code, "$err_count": "1" }); return; } const key = JSON.stringify([error51.id, error51.subtable ?? "", error51.field, error51.code, error51.message]); const current = detailRows.get(key); if (current) { current["$err_count"] = String(Number(current["$err_count"]) + 1); if (error51.subrow !== void 0) { current["$err_subrow"] = `${current["$err_subrow"]},${error51.subrow}`; current["$err_subrow_id"] = `${current["$err_subrow_id"]},${error51.subrowId ?? ""}`; } } else detailRows.set(key, { "$id": error51.id, "$err_field": error51.field, "$err_code": error51.code, "$err_message": error51.message, "$err_value": error51.value, "$err_subtable": error51.subtable ?? "", "$err_subrow": error51.subrow === void 0 ? "" : String(error51.subrow), "$err_subrow_id": error51.subrowId ?? "", "$err_count": "1" }); }; const topTargets = targets.filter((target) => !target.subtableCode); const subtableTargets = /* @__PURE__ */ new Map(); for (const target of targets) { if (!target.subtableCode) continue; const children = subtableTargets.get(target.subtableCode) ?? []; children.push(target); subtableTargets.set(target.subtableCode, children); } for (const row of validationRows) { for (const target of topTargets) { const raw = row.record[target.field.code]?.value; const validation = validateAndNormalizeDmlValue(raw, target.field, numberPrecision); if (!validation.ok) appendError({ id: row.id, field: target.field.code, code: validation.code, message: validation.message, value: renderExistingValidationValue(raw, target.field.fieldType) }); } for (const [tableCode, childTargets] of subtableTargets) { const tableRows2 = row.record[tableCode]?.value; if (!Array.isArray(tableRows2)) continue; for (let i = 0; i < tableRows2.length; i++) { const tableRow = tableRows2[i]; for (const target of childTargets) { const raw = tableRow.value?.[target.field.code]?.value; const validation = validateAndNormalizeDmlValue(raw, target.field, numberPrecision); if (!validation.ok) { const locator = buildValidationCellLocator(tableCode, i, tableRow); appendError({ id: row.id, field: target.field.code, code: validation.code, message: validation.message, value: renderExistingValidationValue(raw, target.field.fieldType), ...locator }); } } } } for (const check2 of evaluateCustomChecks(checkGroups, row.flat, (field) => evaluationTypes.get(field.field))) { appendError({ id: row.id, field: "", code: "ERR_CHECK", message: check2.message, value: "" }); } } if (stmt.summary) rows.push(...summaryRows.values()); else { for (const row of detailRows.values()) { const count = Number(row["$err_count"]); if (row["$err_subtable"] !== "" && count >= 2) { row["$err_message"] = `${row["$err_message"]}\uFF08${count}\u884C: ${row["$err_subrow"]}\uFF09`; } rows.push(row); } } const columns = stmt.summary ? EXISTING_VALIDATION_SUMMARY_COLUMNS : EXISTING_VALIDATION_COLUMNS; const result = { type: "SELECT", columns: [...columns], rows, rowCount: rows.length, validateStats: { errorRecords: errorRecordIds.size, errorCount } }; materializedMetaBySelectResult.set(result, existingValidationColumnMeta(stmt.summary === true)); return result; } var TEMP_TABLE_MAX_ROWS = 1e4; function appendValidationErrors(tempTables, name, columns, rows, maxRows, columnMeta) { const current = tempTables.get(name); if (current && (current.columns.length !== columns.length || current.columns.some((c, i) => c !== columns[i]) || !materializedColumnMetaEqual(current.columnMeta, columnMeta))) { throw new Error(`ArgumentError: validation error table ${name} has a different schema.`); } const existingRows = current?.rows ?? []; if (existingRows.length + rows.length > maxRows) { throw new Error(`ArgumentError: temp table ${name} exceeds max rows (${maxRows}).`); } tempTables.set(name, { columns: [...columns], rows: [...existingRows, ...rows], columnMeta }); } function materializedColumnMetaEqual(left, right) { if (left === right) return true; if (!left || !right || left.size !== right.size) return false; for (const [column, meta3] of left) { const candidate = right.get(column); if (!candidate || candidate.sortKind !== meta3.sortKind || candidate.fieldType !== meta3.fieldType || !fieldSemanticsEqual(candidate.semantics, meta3.semantics)) return false; } return true; } var BatchTimeoutError = class extends Error { constructor() { super("TimeoutError: batch timeout exceeded."); } }; async function executeBatch(sql, client, options = {}) { const statements = parseSqlBatch(sql, options.enableImport === true); const analysis = analyzeBatch(statements); statements.forEach((statement) => assertApplyExecutionScope("phase15b", statement)); if (options.allowApplyMutation !== true && statements.some( (statement) => statementHasMultiValueApply(statement) || statement.type === "UPSERT" && statementHasApplyMutation(statement) )) { throw new Error("UnsupportedError: APPLY mutation requires allowApplyMutation=true"); } const injectedVariables = validateDeclaredBatchVariables(statements, options.variables); const batchOptions = { ...options, variables: injectedVariables }; if (options.continueOnError && analysis.containsDml) { throw new Error("ArgumentError: continueOnError is not allowed for batches containing DML."); } for (const s of analysis.statements) { if (!s.isDml || s.tempTablesReferenced.length === 0) continue; if (s.statementType === "INSERT_SELECT" || s.statementType === "UPSERT_SELECT") continue; const parsed = statements[s.index]; if (parsed?.type === "UPDATE" && parsed.from?.cteName != null) continue; throw new BatchAnalysisError( `ArgumentError: temp table references in ${s.statementType} are not supported yet.`, s.index ); } const metrics = createEmptyMetrics(); const countedClient = wrapClientWithMetrics(client, metrics); const startedAt = Date.now(); const deadline = options.timeoutMs != null ? startedAt + options.timeoutMs : null; const cacheContext = resolveCacheContext(client, options.cacheContext); const tempTables = /* @__PURE__ */ new Map(); const variables = /* @__PURE__ */ new Map(); const results = []; const failed = /* @__PURE__ */ new Set(); let aborted2 = null; for (let i = 0; i < statements.length; i++) { const info = analysis.statements[i]; const base = { index: i, type: info.statementType }; if (aborted2) { results.push({ ...base, status: "skipped", skippedReason: aborted2 }); failed.add(i); continue; } const brokenDep = info.dependsOn.find((d) => failed.has(d)); if (brokenDep !== void 0) { const depName = analysis.statements[brokenDep].tempTablesCreated[0] ?? `statement ${brokenDep}`; results.push({ ...base, status: "skipped", skippedReason: `dependency: ${depName}` }); failed.add(i); continue; } if (deadline !== null && Date.now() >= deadline) { results.push({ ...base, status: "skipped", skippedReason: "timeout" }); failed.add(i); aborted2 = "timeout"; continue; } try { const remaining = deadline !== null ? deadline - Date.now() : null; const userConfirm = batchOptions.confirm; const stmtOptions = userConfirm ? { ...batchOptions, confirm: (count, operation, detailContext) => userConfirm(count, operation, { statementIndex: i, statementCount: statements.length, statementType: info.statementType, targetAppId: info.targetAppId, ...detailContext?.importDetail ? { importDetail: detailContext.importDetail } : {}, ...detailContext?.applyDetail ? { applyDetail: detailContext.applyDetail } : {}, ...detailContext?.applyDiagnostic ? { applyDiagnostic: detailContext.applyDiagnostic } : {} }) } : batchOptions; const searchAbortCollector = { aborted: false }; const statementClient = wrapClientWithSearchAbort( countedClient, searchAbortCollector, info.statementType !== "SELECT" && info.statementType !== "UNION" && info.statementType !== "WITH" ); const cursorScope = wrapClientWithCursorScope(statementClient); const outcome = await runWithDeadline( executeBatchStatement(statements[i], info, cursorScope.client, stmtOptions, cacheContext, tempTables, variables), remaining, cursorScope.closeActive ); if (outcome.result) { outcome.result = attachSearchAbortWarning(outcome.result, searchAbortCollector); } results.push({ ...base, status: "success", ...outcome }); } catch (e) { results.push({ ...base, status: "error", error: toBatchStatementError(e), ...e instanceof RejectLimitExceededError ? { result: e.diagnostic } : {} }); failed.add(i); if (e instanceof BatchTimeoutError) { aborted2 = "timeout"; } else if (e instanceof AssertError) { aborted2 = "assertion"; } else if (info.statementType === "SET_VARIABLE" || info.statementType === "DECLARE_VARIABLE") { aborted2 = "fail-fast"; } else if (!options.continueOnError) { aborted2 = "fail-fast"; } } } metrics.elapsedMs = Date.now() - startedAt; return { ok: results.every((r) => r.status === "success"), statementCount: statements.length, statements: results, analysis, metrics }; } function statementHasApplyMutation(statement) { if (statement.type === "UPDATE" || statement.type === "INSERT") { return statement.validateOnly !== true && Boolean(statement.applyBlocks?.length); } return statement.type === "UPSERT" && statement.validateOnly !== true && Boolean(statement.onInsertApplyBlocks?.length || statement.onUpdateApplyBlocks?.length); } async function executeBatchStatement(stmt, info, client, options, cacheContext, tempTables, variables) { if (stmt.type === "SET_VARIABLE") { const resolvedStmt2 = resolveBatchVariableReferences(stmt, variables); validateKlikeStatement(resolvedStmt2); if (resolvedStmt2.expr.type === "ARRAY") { variables.set(stmt.name, { type: "array", elements: resolvedStmt2.expr.elements.map((element) => ({ type: "string", value: element.value })) }); } else if (resolvedStmt2.expr.type === "SCALAR_SUBQUERY") { try { const value = await evaluateScalarSubquery( resolvedStmt2.expr.query, client, options, cacheContext, tempTables ); const first = resolvedStmt2.expr.query.columns[0]; let numeric = first?.type === "ARITH_COL" || first?.type === "ARITH_AGG_COL" || first?.type === "WINDOW_COL" || first?.type === "AGGREGATE" && (first.func === "COUNT" || first.func === "SUM" || first.func === "AVG" || first.func === "STDDEV_POP" || first.func === "STDDEV_SAMP" || first.func === "VAR_POP" || first.func === "VAR_SAMP" || first.func === "MEDIAN"); if (first?.type === "AGGREGATE" && first.func === "MODE") { const meta3 = (await inferSelectColumnMeta( resolvedStmt2.expr.query, ["__scalar__"], client, cacheContext, tempTables )).get("__scalar__"); numeric = meta3?.semantics?.compareMode === "number" || meta3?.sortKind === "number"; } const numberValue = numeric ? Number(value) : Number.NaN; variables.set(stmt.name, numeric && Number.isFinite(numberValue) ? { type: "number", value: numberValue, raw: value } : { type: "string", value }); } catch (e) { if (e instanceof ScalarSubqueryError) { throw new Error(`ArgumentError: ${e.message}`); } throw e; } } else { variables.set(stmt.name, evaluateScalarExpr(resolvedStmt2.expr)); } return {}; } if (stmt.type === "DECLARE_VARIABLE") { const injected = options.variables ?? {}; if (Object.prototype.hasOwnProperty.call(injected, stmt.name)) { variables.set(stmt.name, { type: "string", value: injected[stmt.name] }); } else { const value = evaluateScalarExpr(stmt.default); variables.set(stmt.name, { type: "string", value: value.type === "number" ? value.raw ?? String(value.value) : value.value }); } return {}; } const resolvedStmt = resolveBatchVariableReferences(stmt, variables); assertApplyScope("phase15b", resolvedStmt); assertApplyExecutionScope("phase15b", resolvedStmt); validateKlikeStatement(resolvedStmt); if (resolvedStmt.type === "VALIDATE") { const result = await executeExistingRecordValidationCore( resolvedStmt, client, { ...options, onLimitReached: "error" }, cacheContext ); if (resolvedStmt.errorTable) { appendValidationErrors( tempTables, resolvedStmt.errorTable, result.columns, result.rows, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, materializedMetaBySelectResult.get(result) ?? existingValidationColumnMeta(resolvedStmt.summary === true) ); } return { result }; } if (resolvedStmt.type === "IMPORT") { return { result: await executeImport(resolvedStmt, client, options, cacheContext, tempTables) }; } if ("validateOnly" in resolvedStmt && resolvedStmt.validateOnly === true) { const result = await executeDmlValidation( resolvedStmt, client, { ...options, onLimitReached: "error" }, cacheContext, tempTables, info.index + 1 ); if (resolvedStmt.validationErrorTable) { appendValidationErrors( tempTables, resolvedStmt.validationErrorTable, result.columns, result.errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, materializedMetaByValidationResult.get(result) ?? /* @__PURE__ */ new Map() ); } return { result }; } if ("onErrorSkip" in resolvedStmt && resolvedStmt.onErrorSkip === true) { return { result: await executeOnErrorSkip( resolvedStmt, client, { ...options, onLimitReached: "error" }, cacheContext, tempTables, info.index + 1 ) }; } if (resolvedStmt.type === "CREATE_TEMP_TABLE") { const materializeOptions = { ...options, maxRecords: options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, onLimitReached: "error" }; const result = await runSelectLike(resolvedStmt.query, client, materializeOptions, cacheContext, tempTables); tempTables.set(resolvedStmt.name, { rows: result.rows, columns: result.columns, columnMeta: materializedMetaBySelectResult.get(result) }); return { tempTable: resolvedStmt.name, rowCount: result.rows.length }; } if (stmt.type === "DROP_TEMP_TABLE") { tempTables.delete(stmt.name); return { tempTable: stmt.name }; } if (stmt.type === "EXPLAIN") { return { result: await executeParsedStatement(resolvedStmt, client, options, cacheContext) }; } if (resolvedStmt.type === "ASSERT") { await executeAssert(resolvedStmt, client, options, cacheContext, tempTables); return {}; } if (info.tempTablesReferenced.length > 0) { if (resolvedStmt.type === "SELECT" || resolvedStmt.type === "UNION") { return { result: await executeQueryWithCte(resolvedStmt, client, options, tempTables, cacheContext) }; } if (resolvedStmt.type === "WITH") { return { result: await executeWith(resolvedStmt, client, options, cacheContext, tempTables) }; } if (resolvedStmt.type === "INSERT_SELECT") { return { result: await executeInsertSelect(resolvedStmt, client, options, cacheContext, tempTables) }; } if (resolvedStmt.type === "UPSERT_SELECT") { return { result: await executeUpsertSelect(resolvedStmt, client, options, cacheContext, tempTables) }; } if (resolvedStmt.type === "UPDATE" && resolvedStmt.from?.cteName != null) { return { result: await executeUpdate(resolvedStmt, client, options, cacheContext, tempTables) }; } throw new Error(`ArgumentError: temp table references in ${stmt.type} are not supported yet.`); } return { result: await executeParsedStatement(resolvedStmt, client, options, cacheContext) }; } async function runSelectLike(query, client, options, cacheContext, tempTables) { if (query.type === "WITH") { return executeWith(query, client, options, cacheContext, tempTables, true); } return executeQueryWithCte(query, client, options, tempTables, cacheContext, true); } async function runWithDeadline(work, remainingMs, onTimeout) { if (remainingMs === null) return work; if (remainingMs <= 0) { if (onTimeout) await onTimeout(); void work.catch(() => { }); throw new BatchTimeoutError(); } let timer; let timedOut = false; const guardedWork = work.then( (value) => timedOut ? new Promise(() => void 0) : value, (error51) => { if (timedOut) return new Promise(() => void 0); throw error51; } ); try { return await Promise.race([ guardedWork, new Promise((_, reject) => { timer = setTimeout(() => { timedOut = true; void (async () => { if (onTimeout) { let cleanupTimer; try { await Promise.race([ onTimeout(), new Promise((resolve3) => { cleanupTimer = setTimeout(resolve3, 5e3); cleanupTimer.unref?.(); }) ]); } finally { if (cleanupTimer) clearTimeout(cleanupTimer); } } reject(new BatchTimeoutError()); })(); }, remainingMs); }) ]); } catch (e) { if (e instanceof BatchTimeoutError) { void work.catch(() => { }); } throw e; } finally { if (timer !== void 0) clearTimeout(timer); } } function toBatchStatementError(e) { if (e instanceof ApplyWritePartialFailureError) { return { code: e.name, message: e.message, partialSuccess: e.partialSuccess }; } if (e instanceof Error) { const name = e.name !== "Error" ? e.name : null; return { code: name ?? codeFromMessagePrefix(e.message), message: e.message }; } if (e !== null && typeof e === "object") { const obj = e; const message2 = typeof obj.message === "string" && obj.message.length > 0 ? obj.message : safeJsonStringify(e); const code = typeof obj.code === "string" && obj.code.length > 0 ? obj.code : codeFromMessagePrefix(message2); return { code, message: message2 }; } const message = String(e); return { code: codeFromMessagePrefix(message), message }; } function codeFromMessagePrefix(message) { return message.match(/^([A-Za-z]+Error):/)?.[1] ?? "Error"; } function safeJsonStringify(v) { try { return JSON.stringify(v) ?? String(v); } catch { return String(v); } } function parseSqlBatch(sql, enableImport = false) { const tokens = new Lexer(sql).tokenize(); return new Parser(tokens, { import: enableImport }).parseStatements(); } function evaluateScalarExpr(expr) { switch (expr.type) { case "STRING": return { type: "string", value: expr.value }; case "NUMBER": return { type: "number", value: expr.value, raw: numberLiteralText(expr) }; case "KINTONE_FUNC": return { type: "string", value: resolveKintoneFunc(expr.name) }; case "STRING_FUNC": return { type: "string", value: evalStringFunc(expr, {}) }; case "ARITH": { const value = evalArithExpr(expr, {}); if (!Number.isFinite(value)) { throw new Error("ArgumentError: SET scalar arithmetic produced a non-finite number."); } return { type: "number", value, raw: String(value) }; } } } function resolveBatchVariableReferences(node, variables) { if (Array.isArray(node)) { return node.map((v) => resolveBatchVariableReferences(v, variables)); } if (node !== null && typeof node === "object") { const obj = node; if (obj["type"] === "VARIABLE" && typeof obj["name"] === "string") { const value = variables.get(obj["name"]); if (value === void 0) { throw new Error(`ParseError: variable @${obj["name"]} is not defined in this batch.`); } if (value.type === "array") { throw new Error(`ParseError: array variable @${obj["name"]} can only be used as IN @${obj["name"]}.`); } return value.type === "number" ? { type: "NUMBER", value: value.value, raw: value.raw ?? String(value.value) } : { type: "STRING", value: value.value }; } if (obj["type"] === "VARIABLE_COL" && typeof obj["name"] === "string" && typeof obj["alias"] === "string") { const value = variables.get(obj["name"]); if (value === void 0) throw new Error(`ParseError: variable @${obj["name"]} is not defined in this batch.`); if (value.type === "array") throw new Error(`ParseError: array variable @${obj["name"]} cannot be used as a SELECT column.`); return value.type === "number" ? { type: "ARITH_COL", expr: { type: "NUMBER", value: value.value, raw: value.raw ?? String(value.value) }, alias: obj["alias"] } : { type: "LITERAL_COL", value: value.value, alias: obj["alias"] }; } if (obj["type"] === "VARIABLE_IN_LIST") return obj; const resolved = Object.fromEntries( Object.entries(obj).map(([key, value]) => [key, resolveBatchVariableReferences(value, variables)]) ); if (resolved["type"] === "BINARY") { const right = resolved["right"]; if (right?.["type"] === "VARIABLE_IN_LIST" && typeof right["name"] === "string") { const value = variables.get(right["name"]); if (value === void 0) throw new Error(`ParseError: variable @${right["name"]} is not defined in this batch.`); if (value.type !== "array") { throw new Error(`ParseError: scalar variable @${right["name"]} cannot be used as IN @${right["name"]}; use IN (@${right["name"]}) instead.`); } if (value.elements.length === 0) { return { type: "BOOLEAN", value: resolved["op"] === "NOT_IN" }; } resolved["right"] = { type: "IN_LIST", values: value.elements.map((element) => ({ type: "STRING", value: element.value })) }; } } const simplified = simplifyBooleanWhere(resolved); if (simplified["type"] === "SELECT" && isBooleanNode(simplified["where"], true)) { simplified["where"] = null; } if ((simplified["type"] === "UPDATE" || simplified["type"] === "DELETE" || simplified["type"] === "REORDER") && isBooleanNode(simplified["where"], true)) { throw new Error("ArgumentError: empty-array simplification makes the target WHERE always true; use an explicit safe target condition."); } return simplified; } return node; } function isBooleanNode(value, expected) { return value !== null && typeof value === "object" && value.type === "BOOLEAN" && (expected === void 0 || value.value === expected); } function simplifyBooleanWhere(obj) { if (obj["type"] === "NOT" && isBooleanNode(obj["expr"])) { return { type: "BOOLEAN", value: !obj["expr"].value }; } if (obj["type"] === "GROUP" && isBooleanNode(obj["expr"])) return obj["expr"]; if (obj["type"] === "LOGICAL") { const left = obj["left"]; const right = obj["right"]; if (obj["op"] === "AND") { if (isBooleanNode(left, false) || isBooleanNode(right, false)) return { type: "BOOLEAN", value: false }; if (isBooleanNode(left, true)) return right; if (isBooleanNode(right, true)) return left; } else if (obj["op"] === "OR") { if (isBooleanNode(left, true) || isBooleanNode(right, true)) return { type: "BOOLEAN", value: true }; if (isBooleanNode(left, false)) return right; if (isBooleanNode(right, false)) return left; } } return obj; } function findVariableRef(node) { if (Array.isArray(node)) { for (const value of node) { const found = findVariableRef(value); if (found !== null) return found; } return null; } if (node !== null && typeof node === "object") { const obj = node; if ((obj["type"] === "VARIABLE" || obj["type"] === "VARIABLE_COL" || obj["type"] === "VARIABLE_IN_LIST") && typeof obj["name"] === "string") return obj["name"]; for (const value of Object.values(obj)) { const found = findVariableRef(value); if (found !== null) return found; } } return null; } var AssertError = class extends Error { constructor(message) { super(`AssertError: ${message}`); this.name = "AssertError"; } }; var ScalarSubqueryError = class extends Error { constructor(message) { super(message); this.name = "ScalarSubqueryError"; } }; async function executeAssert(stmt, client, options, cacheContext, tempTables) { const left = await evalAssertOperand(stmt.left, client, options, cacheContext, tempTables); const semantics = stmt.left.type === "NUMBER" || stmt.left.type === "ARITH" ? syntheticSemantics("number") : syntheticSemantics("string"); if (stmt.op === "BETWEEN") { if (stmt.low === null || stmt.high === null) { throw new Error("ArgumentError: malformed ASSERT statement."); } const low = await evalAssertOperand(stmt.low, client, options, cacheContext, tempTables); const high = await evalAssertOperand(stmt.high, client, options, cacheContext, tempTables); if (!compareScalarValues(">=", left, low, semantics) || !compareScalarValues("<=", left, high, semantics)) { throw new AssertError(`assertion failed: ${stmt.text} (actual: ${left}).`); } return { type: "ASSERT", condition: stmt.text }; } if (stmt.right === null) { throw new Error("ArgumentError: malformed ASSERT statement."); } const right = await evalAssertOperand(stmt.right, client, options, cacheContext, tempTables); if (!compareScalarValues(stmt.op, left, right, semantics)) { throw new AssertError(`assertion failed: ${stmt.text} (actual: ${left}).`); } return { type: "ASSERT", condition: stmt.text }; } async function evalAssertOperand(operand, client, options, cacheContext, tempTables) { switch (operand.type) { case "VARIABLE": throw new Error(`ParseError: unresolved batch variable @${operand.name}.`); case "NUMBER": return numberLiteralText(operand); case "STRING": return operand.value; case "ARITH": return String(evalAssertArith(operand)); case "SCALAR_SUBQUERY": { try { return await evaluateScalarSubquery( operand.query, client, options, cacheContext, tempTables ); } catch (e) { if (e instanceof ScalarSubqueryError) throw new AssertError(e.message); throw e; } } } } async function evaluateScalarSubquery(sourceQuery, client, options, cacheContext, tempTables) { const { query, probed } = withScalarProbeLimit(sourceQuery); const result = await runSubquery(query, client, options, cacheContext, tempTables); if (result.columns.length !== 1) { throw new ScalarSubqueryError( `scalar subquery returned ${result.columns.length} columns (expected 1 column).` ); } if (result.rowCount === 0) { throw new ScalarSubqueryError("scalar subquery returned no rows (expected 1 row)."); } if (result.rowCount > 1) { const rows = probed && result.rowCount === 2 ? "2 or more rows" : `${result.rowCount} rows`; throw new ScalarSubqueryError(`scalar subquery returned ${rows} (expected 1 row).`); } return result.rows[0]?.[result.columns[0]] ?? ""; } function withScalarProbeLimit(query) { const hasAgg = query.groupBy.length > 0 || query.columns.some((c) => c.type === "AGGREGATE" || c.type === "ARITH_AGG_COL"); if (hasAgg || query.distinct || query.limit !== null) return { query, probed: false }; return { query: { ...query, limit: 2 }, probed: true }; } function evalAssertArith(node) { if (node.type === "NUMBER") return node.value; if (node.type === "ARITH") { const left = evalAssertArith(node.left); const right = evalAssertArith(node.right); switch (node.op) { case "+": return left + right; case "-": return left - right; case "*": return left * right; case "/": return left / right; case "%": return left % right; } } throw new Error(`ArgumentError: unsupported operand in ASSERT expression: ${node.type}`); } async function buildWhereFieldSemanticsResolver(stmt, client, cacheContext, materializedTables, forcePhysicalMetadata = false) { const tables = [stmt.from, ...stmt.joins.map((join) => join.table)]; const physicalAppIds = forcePhysicalMetadata || whereNeedsFieldMetadata(stmt.where) ? [...new Set(tables.filter((table) => table.cteName === null).map((table) => table.appId))] : []; const infosByApp = new Map( await Promise.all(physicalAppIds.map(async (appId) => { const infos = await getFieldsCached(appId, client, cacheContext); return [appId, new Map(infos.map((info) => [info.code, info]))]; })) ); const orderedFields = /* @__PURE__ */ new Set(); const collectOrderedFields = (node) => { if (Array.isArray(node)) { node.forEach(collectOrderedFields); return; } if (node === null || typeof node !== "object") return; const value = node; if (value["type"] === "SELECT") return; if (value["type"] === "BINARY" && [">", "<", ">=", "<="].includes(String(value["op"]))) { const left = value["left"]; if (left?.["type"] === "FIELD" && typeof left["field"] === "string") { orderedFields.add(left["field"]); } } Object.values(value).forEach(collectOrderedFields); }; collectOrderedFields(stmt.where); collectOrderedFields(stmt.having); for (const column of stmt.columns) { if (column.type === "CASE_COL") collectOrderedFields(column.expr); } const statusOrdersByApp = /* @__PURE__ */ new Map(); await Promise.all([...infosByApp].map(async ([appId, infos]) => { const needsStatus = [...orderedFields].some((field) => infos.get(field)?.fieldType === "STATUS"); if (!needsStatus) return; const order = await loadProcessStatusOrder(appId, client, cacheContext); if (order) statusOrdersByApp.set(appId, order); })); const fromPhysical = (table, field, allowSubtableSystemColumns) => { if (field === "$id") return withFieldSemanticSource( resolveFieldSemantics({ fieldType: "__ID__" }), table.appId, "$id" ); if (allowSubtableSystemColumns && table.subtableCode) { if (field === "_rid") return syntheticSemantics("string"); if (field === "_idx" || field === "_pid") return syntheticSemantics("number"); } const info = infosByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, field)); if (!info) return void 0; const base = info.semantics ?? resolveFieldSemantics(info); const semantics = info.fieldType === "STATUS" && statusOrdersByApp.has(table.appId) ? { ...base, optionOrder: statusOrdersByApp.get(table.appId) } : base; return withFieldSemanticSource( semantics, table.appId, info.code ); }; return (field) => { if (field.tableAlias !== null) { if (field.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { return fromPhysical(stmt.from, field.field, false); } const table = tables.find((candidate) => effectiveTableAlias(candidate) === field.tableAlias); if (!table) return void 0; if (table.cteName !== null) { return materializedTables?.get(table.cteName)?.columnMeta?.get(field.field)?.semantics ?? syntheticSemantics("string"); } return fromPhysical(table, field.field, true); } if (stmt.joins.length === 0) { if (stmt.from.cteName !== null) { return materializedTables?.get(stmt.from.cteName)?.columnMeta?.get(field.field)?.semantics ?? syntheticSemantics("string"); } return fromPhysical(stmt.from, field.field, true); } const matches = tables.flatMap((table) => { const semantics = table.cteName !== null ? materializedTables?.get(table.cteName)?.columnMeta?.get(field.field)?.semantics : fromPhysical(table, field.field, true); return semantics ? [semantics] : []; }); if (matches.length === 1) return matches[0]; if (tables.some((table) => subtableSystemFieldType(table, field.field) !== void 0)) return void 0; return matches.length > 1 ? syntheticSemantics("string") : void 0; }; } function selectCaseConditionsNeedFieldMetadata(stmt) { const visit = (value) => { if (value === null || typeof value !== "object") return false; if (Array.isArray(value)) return value.some(visit); const node = value; if (node.type === "CASE_WHEN" && node.branches?.some((branch) => whereNeedsFieldMetadata(branch.condition))) return true; return Object.values(node).some(visit); }; return stmt.columns.some(visit); } function buildHavingFieldSemanticsResolver(stmt, rowResolver) { const aliases = /* @__PURE__ */ new Map(); for (const column of stmt.columns) { if (!("alias" in column) || !column.alias) continue; let semantics; if (column.type === "FIELD") semantics = rowResolver(aggregateFieldRef(column.field)); else if (column.type === "ARITH_COL" || column.type === "ARITH_AGG_COL" || column.type === "WINDOW_COL") { semantics = syntheticSemantics("number"); } else if (column.type === "AGGREGATE") { if (column.func === "MIN" || column.func === "MAX" || column.func === "MODE") { if (column.arg.type !== "WILDCARD") { semantics = inferAggregateArgMeta(column.arg, (ref) => { const resolved = rowResolver(ref); if (!resolved) return void 0; return { sortKind: resolved.compareMode === "number" || resolved.compareMode === "recordNumber" ? "number" : "string", fieldType: resolved.fieldType, semantics: resolved }; }).semantics; } } else { semantics = column.func === "GROUP_CONCAT" ? syntheticSemantics("string") : syntheticSemantics("number"); } } else if (column.type === "STRFUNC_COL") { semantics = stringFunctionColumnMeta(column.expr).semantics; } else if (column.type === "LITERAL_COL" || column.type === "SCALAR_SUBQUERY_COL" || column.type === "CASE_COL" || column.type === "SCALAR_VALUE_COL") { semantics = syntheticSemantics("string"); } if (semantics) aliases.set(column.alias, semantics); } return (field) => field.tableAlias === null && aliases.has(field.field) ? aliases.get(field.field) : rowResolver(field); } async function resolveSelectWhereCapability(stmt, client, cacheContext, materializedTables) { if (stmt.where === null) return classifyWhereCapability(null, () => void 0); const resolver = await buildWhereFieldSemanticsResolver(stmt, client, cacheContext, materializedTables); return classifyWhereCapability(stmt.where, resolver); } function formatWhereCapabilityFailure(result) { const reason = result.reasons.find( (candidate) => candidate.code === "WHERE_FIELD_UNRESOLVED" || candidate.code === "WHERE_OPERATOR_UNSUPPORTED" ) ?? result.reasons[0]; const details = [ reason?.field ? `field=${reason.field}` : null, reason?.fieldType ? `type=${reason.fieldType}` : null, reason?.operator ? `operator=${reason.operator}` : null, reason?.code ? `reason=${reason.code}` : null ].filter((value) => value !== null).join(", "); return details || "reason=WHERE_UNSUPPORTED"; } function hasCanonicalOrder(stmt) { return stmt.orderBy.length > 0 || stmt.columns.some( (column) => column.type === "WINDOW_COL" && column.orderBy.length > 0 ); } async function assertDmlWhereCapability(stmt, client, cacheContext) { if (stmt.subtableCode || stmt.type === "UPDATE" && stmt.from != null) return; const fields = whereNeedsFieldMetadata(stmt.where) ? await getFieldsCached(stmt.appId, client, cacheContext) : []; const byCode = new Map(fields.map((field) => [field.code, field])); if (stmt.where.type === "BOOLEAN" && stmt.where.value === false) return; const result = classifyWhereCapability(stmt.where, (field) => { if (field.field === "$id") return resolveFieldSemantics({ fieldType: "__ID__" }); const info = byCode.get(field.field); return info?.semantics ?? (info ? resolveFieldSemantics(info) : void 0); }); if (result.capability !== "EXACT_PUSHDOWN") { throw new DmlConvertError( `WHERE predicate cannot be represented by kintone REST (${formatWhereCapabilityFailure(result)})` ); } } async function executeSelect(stmt, client, options, cacheContext, cteCache, captureColumnMeta = false) { let result; if (isNoFromSelect(stmt)) { result = executeNoFromSelect(stmt); if (captureColumnMeta) { materializedMetaBySelectResult.set(result, await inferSelectColumnMeta(stmt, result.columns, client, cacheContext, cteCache)); } return result; } await resolveSelectCaseSubqueries(stmt, client, options, cacheContext, cteCache); const whereCapability = await resolveSelectWhereCapability(stmt, client, cacheContext, cteCache); if (whereCapability.capability === "UNSUPPORTED") { throw new Error(`ArgumentError: WHERE predicate is unsupported (${formatWhereCapabilityFailure(whereCapability)}).`); } const staticMode = resolveSelectMode(stmt); const mode = whereCapability.capability === "EXACT_PUSHDOWN" ? staticMode : "FULL_SCAN"; const orderMeta = await buildOrderByMetaForSelect(stmt, client, cacheContext, cteCache); const orderPlan = hasCanonicalOrder(stmt) ? (stmt.orderMode === "KINTONE_NATIVE" ? planKorder : planCanonicalOrder)({ stmt, staticMode: mode, whereCapability: whereCapability.capability, orderSemantics: orderMeta.semantics, maxRecords: options.maxRecords ?? 1e4, hasKlike: whereHasKlike(stmt.where) }) : null; await validateSelectFieldCodes( stmt, orderPlan?.kind === "CANONICAL_LOCAL" ? "FULL_SCAN" : mode, client, cacheContext ); const completeReasons = orderPlan?.kind === "CANONICAL_REST_TOP_N" || orderPlan?.kind === "KORDER_NATIVE" || orderPlan?.kind === "KORDER_CURSOR" ? completeInputReasons({ ...stmt, orderBy: [] }) : completeInputReasons(stmt); const completeInputRequired = completeReasons.size > 0; const truncateWasDisabled = completeInputRequired && options.onLimitReached === "truncate"; const effectiveOptions = truncateWasDisabled ? { ...options, onLimitReached: "error" } : options; try { if (mode === "SIMPLE") { result = await executeSimpleSelect(stmt, client, effectiveOptions, cacheContext, orderPlan, orderMeta); } else { result = await executeFullScanSelect( stmt, client, effectiveOptions, cacheContext, cteCache, whereCapability.capability === "EXACT_PUSHDOWN", orderMeta ); } } catch (error51) { if (completeInputRequired && error51 instanceof FetchAllLimitError) { throw new FetchAllLimitError( completeInputErrorPrefix(completeReasons) + (truncateWasDisabled ? "onLimit=truncate\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002" : "") + error51.message ); } throw error51; } if (captureColumnMeta) { materializedMetaBySelectResult.set(result, await inferSelectColumnMeta(stmt, result.columns, client, cacheContext, cteCache)); } return result; } function completeInputErrorPrefix(reasons) { const reasonList = [...reasons].join(", "); const subject = reasons.size === 1 && reasons.has("STATISTICAL_AGGREGATE") ? "\u7D71\u8A08\u96C6\u7D04\u306E\u6B63\u3057\u3044\u7D50\u679C" : "ORDER BY\u306E\u6B63\u3057\u3044\u7D50\u679C"; return `${subject}\u306B\u306F\u5B8C\u5168\u306A\u5019\u88DC\u96C6\u5408\u304C\u5FC5\u8981\u3067\u3059\u3002complete input reason: ${reasonList}\u3002`; } function isConstantFalseWhere(where) { return where?.type === "BOOLEAN" && where.value === false; } function isNoFromSelect(stmt) { return stmt.from.appId === 0 && stmt.from.cteName === NO_FROM_CTE_NAME; } function arithHasFieldRef(node) { if (node.type === "FIELD_REF") return true; if (node.type === "ARITH") return arithHasFieldRef(node.left) || arithHasFieldRef(node.right); if (node.type === "STRING_FUNC") return stringFuncHasFieldRef(node); return false; } function stringFuncArgHasFieldRef(arg) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") return true; return scalarValueHasFieldRef(arg); } function scalarValueHasFieldRef(expr) { if (expr.type === "FIELD") return true; if (expr.type === "STRING_FUNC") return stringFuncHasFieldRef(expr); if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { return scalarValueHasFieldRef(expr.left) || scalarValueHasFieldRef(expr.right); } if (expr.type === "CASE_WHEN") { const results = [...expr.branches.map((branch) => branch.result), ...expr.elseResult ? [expr.elseResult] : []]; return results.some((result) => result.type !== "ARRAY" && (result.type === "FIELD_REF" || result.type === "ARITH" ? arithHasFieldRef(result) : scalarValueHasFieldRef(result))); } return false; } function stringFuncHasFieldRef(expr) { return expr.args.some((arg) => stringFuncArgHasFieldRef(arg)); } function validateNoFromColumns(stmt) { for (const col of stmt.columns) { switch (col.type) { case "VARIABLE_COL": throw new Error(`internal error: unresolved SELECT variable @${col.name}`); case "LITERAL_COL": break; case "ARITH_COL": if (arithHasFieldRef(col.expr)) { throw new Error("ArgumentError: field reference is not allowed without FROM."); } break; case "STRFUNC_COL": if (stringFuncHasFieldRef(col.expr)) { throw new Error("ArgumentError: field reference is not allowed without FROM."); } break; case "SCALAR_VALUE_COL": if (scalarValueHasFieldRef(col.expr)) { throw new Error("ArgumentError: field reference is not allowed without FROM."); } break; case "WINDOW_COL": if (col.partitionBy.length > 0 || col.orderBy.length > 0) { throw new Error("ArgumentError: field reference is not allowed without FROM."); } break; default: throw new Error(`ArgumentError: ${col.type} is not supported without FROM.`); } } } function executeNoFromSelect(stmt) { if (stmt.joins.length > 0 || stmt.where || stmt.groupBy.length > 0 || stmt.having || stmt.orderBy.length > 0 || stmt.distinct) { throw new Error("ArgumentError: JOIN/WHERE/GROUP BY/HAVING/ORDER BY/DISTINCT are not supported without FROM."); } validateNoFromColumns(stmt); const windowed = applyWindow([{}], stmt.columns); const { rows: projected, columns } = project(windowed, stmt.columns); const rows = applyLimit(projected, stmt.limit, stmt.offset); return { type: "SELECT", rows, columns, rowCount: rows.length, warnings: [] }; } async function executeSimpleSelect(stmt, client, options, cacheContext, orderPlan, orderMeta) { const restStmt = orderPlan?.kind === "CANONICAL_REST_TOP_N" ? withCanonicalRestTie(stmt) : stmt; const params = selectToKintoneParams(restStmt); const fetchFields = orderPlan?.kind === "CANONICAL_LOCAL" ? selectToFetchAllFields(stmt, stmt.from) : params.fields; const typedInFieldTypes = await loadTypedInFieldTypes(stmt, client, cacheContext); const fieldTypeResolvers = buildSelectFieldTypeResolvers(stmt, typedInFieldTypes); const projectionSemanticsResolver = stmt.columns.some((column) => column.type === "CASE_COL") ? await buildWhereFieldSemanticsResolver( stmt, client, cacheContext, void 0, selectCaseConditionsNeedFieldMetadata(stmt) ) : void 0; const maxRecords2 = options.maxRecords ?? 1e4; const warnings = /* @__PURE__ */ new Set(); const onLimit2 = options.onLimitReached ?? "error"; const parallel = options.fetchParallel ?? 1; const useRestWindow = stmt.orderBy.length > 0 ? orderPlan?.kind === "CANONICAL_REST_TOP_N" || orderPlan?.kind === "KORDER_NATIVE" || orderPlan?.kind === "KORDER_CURSOR" : stmt.limit !== null && stmt.limit <= 500; const needed = stmt.limit === null ? null : (stmt.offset ?? 0) + stmt.limit; const stopAfter = stmt.orderBy.length === 0 && needed !== null && needed <= maxRecords2 && !whereHasKlike(stmt.where) ? needed : void 0; let records; if ((orderPlan?.kind === "KORDER_NATIVE" || orderPlan?.kind === "KORDER_CURSOR") && stmt.limit === 0) { records = []; } else if (orderPlan?.kind === "KORDER_CURSOR") { const cursorResult = await executeKorderCursor({ client, app: params.app, fields: params.fields, query: buildKorderCursorQuery(stmt), offset: stmt.offset ?? 0, limit: stmt.limit }); records = cursorResult.records; if (cursorResult.cleanupWarning) warnings.add(cursorResult.cleanupWarning); } else if (useRestWindow) { const res = await client.getRecords({ app: params.app, query: params.query, fields: params.fields }); records = res.records; } else { const baseQuery = stmt.where ? whereToKintone(stmt.where) : ""; records = await fetchAll( client.getRecords, params.app, baseQuery, fetchFields, { parallel, maxRecords: maxRecords2, stopAfter, onLimit: onLimit2, onTruncate: (max) => { warnings.add(`\u53D6\u5F97\u4E0A\u9650\uFF08${max} \u4EF6\uFF09\u306B\u9054\u3057\u305F\u305F\u3081\u3001${max} \u4EF6\u3067\u6253\u3061\u5207\u3063\u3066\u8868\u793A\u3057\u3066\u3044\u307E\u3059\u3002`); } } ); } let rows = records.map((r) => flatten(r, null)); if (!useRestWindow) { rows = applyOrderBy( rows, stmt.orderBy, orderMeta.optionOrders, orderMeta.sortKinds, orderMeta.semantics, buildOrderByAliasEvaluator( stmt.columns, void 0, fieldTypeResolvers.row, projectionSemanticsResolver ) ); rows = applyLimit(rows, stmt.limit, stmt.offset); } const { rows: projected, columns } = project( rows, stmt.columns, void 0, fieldTypeResolvers.row, void 0, projectionSemanticsResolver ); return { type: "SELECT", rows: projected, columns, rowCount: projected.length, warnings: [...warnings] }; } async function validateSelectFieldCodes(stmt, mode, client, cacheContext) { const appToFields = /* @__PURE__ */ new Map(); const addFields = (appId, fields) => { if (fields.length === 0) return; let target = appToFields.get(appId); if (!target) { target = /* @__PURE__ */ new Set(); appToFields.set(appId, target); } for (const f of fields) target.add(f); }; if (mode === "SIMPLE") { const params = selectToKintoneParams(stmt); addFields(params.app, params.fields); } else { const tables = [stmt.from, ...stmt.joins.map((j) => j.table)].filter((t) => t.cteName === null); for (const table of tables) { addFields(table.appId, selectToFetchAllFields(stmt, table)); } } for (const [appId, fields] of appToFields.entries()) { const userFields = [...fields].filter((f) => !isSystemLikeFieldCode(f)); if (userFields.length === 0) continue; const defs = await getFieldsCached(appId, client, cacheContext); if (defs.length === 0) continue; const validCodes = new Set(defs.map((d) => d.code)); const unknown2 = userFields.filter((f) => !validCodes.has(f)); if (unknown2.length > 0) { throw new Error(`ArgumentError: unknown field code(s): ${unknown2.join(", ")} (APP${appId})`); } } } function extractMainTypedPushdownCandidate(stmt) { if (stmt.where === null || stmt.from.subtableCode || stmt.from.cteName !== null) return null; if (stmt.joins.length === 0) { return extractTypedPushdownCandidates(stmt.where, { tableAlias: stmt.from.alias ?? void 0, allowUnqualifiedFields: true }); } if (!stmt.from.alias) return null; return extractTypedPushdownCandidates(stmt.where, { tableAlias: stmt.from.alias }); } async function loadTypedPushdownMeta(stmt, client, cacheContext) { const candidatesByApp = /* @__PURE__ */ new Map(); const addCandidate = (appId, candidate) => { if (candidate === null) return; const existing = candidatesByApp.get(appId); if (existing) existing.push(candidate); else candidatesByApp.set(appId, [candidate]); }; addCandidate(stmt.from.appId, extractMainTypedPushdownCandidate(stmt)); if (stmt.where !== null) { for (const join of stmt.joins) { if (!join.table.alias || join.table.subtableCode || join.table.cteName !== null) continue; const candidate = extractTypedPushdownCandidates(stmt.where, { tableAlias: join.table.alias }); addCandidate(join.table.appId, candidate); } } const entries = await Promise.all([...candidatesByApp.entries()].map(async ([appId, candidates]) => { const [fieldTypes, fieldOptions] = await Promise.all([ getFieldTypeMap(appId, client, cacheContext), getFieldOptionSetMapByApp(appId, client, cacheContext) ]); const statusFields = collectCandidateFieldCodes(candidates).filter((fieldCode) => fieldTypes.get(fieldCode) === "STATUS"); if (statusFields.length > 0) { const process4 = await getProcessStatusesCached(appId, client, cacheContext); if (process4.enable && process4.states && process4.states.length > 0) { const states = new Set(process4.states.map((state) => state.name)); for (const fieldCode of statusFields) fieldOptions.set(fieldCode, states); } } return [appId, fieldTypes, fieldOptions]; })); return { fieldTypesByApp: new Map(entries.map(([appId, fieldTypes]) => [appId, fieldTypes])), fieldOptionsByApp: new Map(entries.map(([appId, , fieldOptions]) => [appId, fieldOptions])) }; } function collectCandidateFieldCodes(candidates) { const fields = /* @__PURE__ */ new Set(); const visit = (expr) => { if (expr.type === "BINARY") { if (expr.left.type === "FIELD") fields.add(expr.left.field); return; } if (expr.type === "LOGICAL") { visit(expr.left); visit(expr.right); return; } if (expr.type === "GROUP" || expr.type === "NOT") visit(expr.expr); }; for (const candidate of candidates) visit(candidate); return [...fields]; } function collectTypedInFieldRefs(expr, out) { if (expr === null) return; switch (expr.type) { case "BINARY": if ((expr.op === "IN" || expr.op === "NOT_IN") && expr.left.type === "FIELD") { out.push(expr.left); } if (expr.left.type === "CASE_FIELD") collectCaseTypedInFieldRefs(expr.left.expr, out); if (expr.right.type === "CASE_VALUE") collectCaseTypedInFieldRefs(expr.right.expr, out); return; case "LOGICAL": collectTypedInFieldRefs(expr.left, out); collectTypedInFieldRefs(expr.right, out); return; case "NOT": case "GROUP": collectTypedInFieldRefs(expr.expr, out); return; case "NULL_CHECK": case "EXISTS": case "BOOLEAN": return; } } function collectCaseTypedInFieldRefs(expr, out) { for (const branch of expr.branches) collectTypedInFieldRefs(branch.condition, out); } function collectSelectTypedInFieldRefs(stmt) { const refs = []; collectTypedInFieldRefs(stmt.where, refs); collectTypedInFieldRefs(stmt.having, refs); for (const column of stmt.columns) { if (column.type === "CASE_COL") collectCaseTypedInFieldRefs(column.expr, refs); } return refs; } function effectiveTableAlias(table) { return table.alias ?? table.cteName; } function findTableForAlias(stmt, alias) { return [stmt.from, ...stmt.joins.map((join) => join.table)].find((table) => effectiveTableAlias(table) === alias); } function physicalSelectTables(stmt) { return [stmt.from, ...stmt.joins.map((join) => join.table)].filter((table) => table.cteName === null); } async function loadTypedInFieldTypes(stmt, client, cacheContext) { const refs = collectSelectTypedInFieldRefs(stmt); if (refs.length === 0) return /* @__PURE__ */ new Map(); const appIds = /* @__PURE__ */ new Set(); const physicalTables = physicalSelectTables(stmt); for (const ref of refs) { if (ref.tableAlias !== null) { if (ref.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { appIds.add(stmt.from.appId); continue; } const table = findTableForAlias(stmt, ref.tableAlias); if (table && table.cteName === null) appIds.add(table.appId); continue; } if (stmt.joins.length === 0) { if (stmt.from.cteName === null) appIds.add(stmt.from.appId); continue; } for (const table of physicalTables) appIds.add(table.appId); } const entries = await Promise.all([...appIds].map(async (appId) => [appId, await getFieldTypeMap(appId, client, cacheContext)])); return new Map(entries); } function aggregateFieldRef(field) { const dot = field.indexOf("."); return dot > 0 ? { type: "FIELD", tableAlias: field.slice(0, dot), field: field.slice(dot + 1) } : { type: "FIELD", tableAlias: null, field }; } function collectAggregateRef(func, arg, out) { if (func !== "MIN" && func !== "MAX" && func !== "MODE" || arg.type === "WILDCARD") return; collectAggregateArgFieldRefs(arg, out); } function collectAggregateArgFieldRefs(arg, out) { if (arg.type === "FIELD_REF") { out.push(aggregateFieldRef(arg.field)); return; } if (arg.type === "FIELD") { out.push(arg); return; } if (arg.type === "ARITH") { collectAggregateArgFieldRefs(arg.left, out); collectAggregateArgFieldRefs(arg.right, out); return; } if (arg.type === "SCALAR_ARITH" || arg.type === "CONCAT_OP") { collectAggregateArgFieldRefs(arg.left, out); collectAggregateArgFieldRefs(arg.right, out); return; } if (arg.type === "STRING_FUNC") { for (const child of arg.args) { if (child.type !== "AGG_REF" && child.type !== "AGG_ARITH") collectAggregateArgFieldRefs(child, out); } return; } if (arg.type === "CASE_WHEN") { for (const result of [...arg.branches.map((branch) => branch.result), ...arg.elseResult ? [arg.elseResult] : []]) { if (result.type !== "ARRAY") collectAggregateArgFieldRefs(result, out); } } } function collectAggregateOperandRefs(node, out) { if (node.type === "AGG_REF") { collectAggregateRef(node.func, node.arg, out); return; } if (node.type === "AGG_ARITH") { collectAggregateOperandRefs(node.left, out); collectAggregateOperandRefs(node.right, out); } } function collectStringFuncAggregateRefs(expr, out) { for (const arg of expr.args) { if (arg.type === "AGG_REF" || arg.type === "AGG_ARITH") { collectAggregateOperandRefs(arg, out); } else { collectScalarAggregateRefs(arg, out); } } } function collectScalarAggregateRefs(expr, out) { if (expr.type === "STRING_FUNC") { collectStringFuncAggregateRefs(expr, out); return; } if (expr.type === "SCALAR_ARITH" || expr.type === "CONCAT_OP") { collectScalarAggregateRefs(expr.left, out); collectScalarAggregateRefs(expr.right, out); return; } if (expr.type === "CASE_WHEN") { const results = [...expr.branches.map((branch) => branch.result), ...expr.elseResult ? [expr.elseResult] : []]; for (const result of results) { if (result.type === "STRING_FUNC") collectStringFuncAggregateRefs(result, out); else if (result.type !== "ARRAY" && result.type !== "FIELD_REF" && result.type !== "ARITH") collectScalarAggregateRefs(result, out); } } } function collectSelectAggregateSortRefs(columns) { const refs = []; for (const column of columns) { if (column.type === "AGGREGATE") { collectAggregateRef(column.func, column.arg, refs); } else if (column.type === "ARITH_AGG_COL") { collectAggregateOperandRefs(column.expr, refs); } else if (column.type === "STRFUNC_COL") { collectStringFuncAggregateRefs(column.expr, refs); } else if (column.type === "SCALAR_VALUE_COL") { collectScalarAggregateRefs(column.expr, refs); } } return refs; } var AGGREGATE_STRING_FIELD_TYPES = /* @__PURE__ */ new Set([ "SINGLE_LINE_TEXT", "MULTI_LINE_TEXT", "RICH_TEXT", "LINK", "DROP_DOWN", "RADIO_BUTTON", "STATUS", "DATE", "TIME", "DATETIME", "CREATED_TIME", "UPDATED_TIME" ]); function aggregateSortKind(info) { if (info.sortKind !== void 0) return info.sortKind; if (info.fieldType === "NUMBER" || info.fieldType === "RECORD_NUMBER") return "number"; return AGGREGATE_STRING_FIELD_TYPES.has(info.fieldType) ? "string" : void 0; } async function loadAggregateSortKindResolver(stmt, client, cacheContext, materializedTables) { const refs = collectSelectAggregateSortRefs(stmt.columns); if (refs.length === 0) return void 0; const appIds = /* @__PURE__ */ new Set(); const physicalTables = physicalSelectTables(stmt); for (const ref of refs) { if (ref.tableAlias !== null) { if (ref.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { appIds.add(stmt.from.appId); continue; } const table = findTableForAlias(stmt, ref.tableAlias); if (table && table.cteName === null) appIds.add(table.appId); } else if (stmt.joins.length === 0) { if (stmt.from.cteName === null) appIds.add(stmt.from.appId); } else { for (const table of physicalTables) appIds.add(table.appId); } } const fieldInfosByApp = new Map( await Promise.all([...appIds].map(async (appId) => { const infos = await getFieldsCached(appId, client, cacheContext); return [appId, new Map(infos.map((info) => [info.code, info]))]; })) ); const statusOrdersByApp = /* @__PURE__ */ new Map(); const aggregateFieldNames = new Set(refs.map((ref) => ref.field)); await Promise.all([...fieldInfosByApp].map(async ([appId, infos]) => { if (![...aggregateFieldNames].some((field) => infos.get(field)?.fieldType === "STATUS")) return; const order = await loadProcessStatusOrder(appId, client, cacheContext); if (order) statusOrdersByApp.set(appId, order); })); const tables = [stmt.from, ...stmt.joins.map((join) => join.table)]; const semanticsForInfo = (info, appId) => { const base = info.semantics ?? resolveFieldSemantics(info); return info.fieldType === "STATUS" && statusOrdersByApp.has(appId) ? { ...base, optionOrder: statusOrdersByApp.get(appId) } : base; }; const resolveRef2 = (ref) => { let info; if (ref.tableAlias !== null) { if (ref.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { info = fieldInfosByApp.get(stmt.from.appId)?.get(ref.field); } else { const table = tables.find((candidate) => effectiveTableAlias(candidate) === ref.tableAlias); if (!table) return void 0; if (table.cteName !== null) { return materializedTables?.get(table.cteName)?.columnMeta?.get(ref.field)?.semantics ?? syntheticSemantics("string"); } info = fieldInfosByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, ref.field)); } } else if (stmt.joins.length === 0) { if (stmt.from.cteName !== null) { return materializedTables?.get(stmt.from.cteName)?.columnMeta?.get(ref.field)?.semantics ?? syntheticSemantics("string"); } info = fieldInfosByApp.get(stmt.from.appId)?.get(fieldCodeForTypeLookup(stmt.from, ref.field)); } else { const matches = tables.flatMap((table) => { if (table.cteName !== null) { const materialized = materializedTables?.get(table.cteName); return materialized?.columns.includes(ref.field) ? [materialized.columnMeta?.get(ref.field)?.semantics ?? syntheticSemantics("string")] : []; } const candidate = fieldInfosByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, ref.field)); return candidate ? [semanticsForInfo(candidate, table.appId)] : []; }); if (matches.length !== 1) return void 0; return matches[0]; } if (!info) return void 0; const sourceTable = ref.tableAlias !== null ? tables.find((table) => effectiveTableAlias(table) === ref.tableAlias) : stmt.joins.length === 0 ? stmt.from : void 0; return semanticsForInfo(info, sourceTable?.appId ?? stmt.from.appId); }; return resolveRef2; } function fieldCodeForTypeLookup(table, field) { if (table.subtableCode && field.startsWith("_p.")) return field.slice(3); return field; } function subtableSystemFieldType(table, field) { if (!table.subtableCode) return void 0; if (field === "_rid") return "SINGLE_LINE_TEXT"; if (field === "_idx" || field === "_pid") return "NUMBER"; return void 0; } function materializedMetaFromFieldInfo(info, sourceAppId) { const semantics = info.semantics ?? resolveFieldSemantics(info); return { sortKind: aggregateSortKind(info), fieldType: info.fieldType, semantics: sourceAppId === void 0 ? semantics : withFieldSemanticSource(semantics, sourceAppId, info.code) }; } function withCanonicalRestTie(stmt) { const hasId = stmt.orderBy.some( (item) => item.key.type === "FIELD_NAME" && item.key.name === "$id" ); return hasId ? stmt : { ...stmt, orderBy: [...stmt.orderBy, { key: { type: "FIELD_NAME", name: "$id" }, direction: "ASC" }] }; } function syntheticColumnMeta(compareMode) { return { sortKind: compareMode, semantics: syntheticSemantics(compareMode) }; } function unknownStringColumnMeta() { return { semantics: syntheticSemantics("string", "KSQL_UNKNOWN") }; } function unsupportedColumnMeta(fieldType = "KSQL_ARRAY") { return { semantics: { fieldType, compareMode: "unsupported", inSubtable: false, requiresCollectionOperators: false } }; } function systemColumnMeta(field) { if (field === "$id") { return { sortKind: "number", fieldType: "__ID__", semantics: resolveFieldSemantics({ fieldType: "__ID__" }) }; } if (field === "_rid") return syntheticColumnMeta("string"); if (field === "_pid" || field === "_idx") return syntheticColumnMeta("number"); if (field === "$revision") return syntheticColumnMeta("number"); return void 0; } var NUMBER_RETURNING_STRING_FUNCTIONS = /* @__PURE__ */ new Set([ "LENGTH", "LENGTH_CHAR", "INSTR", "ROUND", "FLOOR", "CEIL", "TRUNCATE", "YEAR", "MONTH", "DAY", "DATEDIFF", "ABS", "MOD", "POWER", "SQRT", "DAYOFWEEK", "QUARTER", "WEEK" ]); function stringFunctionColumnMeta(expr) { if (expr.func === "CAST") { const target = expr.args[1]; return target?.type === "STRING" && target.value === "NUMBER" ? syntheticColumnMeta("number") : syntheticColumnMeta("string"); } return NUMBER_RETURNING_STRING_FUNCTIONS.has(expr.func) ? syntheticColumnMeta("number") : syntheticColumnMeta("string"); } function caseResultColumnMeta(result, resolveField2) { if (result.type === "STRING") return syntheticColumnMeta("string"); if (result.type === "ARRAY") return unsupportedColumnMeta(); if (result.type === "NUMBER" || result.type === "ARITH" || result.type === "SCALAR_ARITH") return syntheticColumnMeta("number"); if (result.type === "STRING_FUNC") return stringFunctionColumnMeta(result); if (result.type === "FIELD_REF") return resolveField2(aggregateFieldRef(result.field)) ?? unknownStringColumnMeta(); if (result.type === "FIELD") return resolveField2(result) ?? unknownStringColumnMeta(); return unknownStringColumnMeta(); } function mergeExpressionColumnMeta(candidates) { if (candidates.length === 0) return unknownStringColumnMeta(); const first = candidates[0]; const withoutSource = (semantics) => { if (!semantics) return void 0; const { source: _source, ...rest } = semantics; return rest; }; if (candidates.every( (candidate) => candidate.sortKind === first.sortKind && candidate.fieldType === first.fieldType && fieldSemanticsEqual(withoutSource(candidate.semantics), withoutSource(first.semantics)) )) { const sameSource = candidates.every( (candidate) => fieldSemanticsEqual(candidate.semantics, first.semantics) ); return sameSource ? first : { ...first, semantics: withoutSource(first.semantics) }; } if (candidates.some((candidate) => candidate.semantics?.compareMode === "unsupported")) { return unsupportedColumnMeta("KSQL_MIXED_UNSUPPORTED"); } return unknownStringColumnMeta(); } function inferAggregateArgMeta(arg, resolveField2) { if (arg.type === "FIELD_REF") return resolveField2(aggregateFieldRef(arg.field)) ?? unknownStringColumnMeta(); if (arg.type === "FIELD") return resolveField2(arg) ?? unknownStringColumnMeta(); if (arg.type === "NUMBER" || arg.type === "ARITH" || arg.type === "SCALAR_ARITH") return syntheticColumnMeta("number"); if (arg.type === "STRING" || arg.type === "CONCAT_OP" || arg.type === "VARIABLE") return syntheticColumnMeta("string"); if (arg.type === "STRING_FUNC") return stringFunctionColumnMeta(arg); const results = arg.branches.map((branch) => caseResultColumnMeta(branch.result, resolveField2)); if (arg.elseResult) results.push(caseResultColumnMeta(arg.elseResult, resolveField2)); return mergeExpressionColumnMeta(results); } function selectNeedsSourceColumnMeta(stmt) { return stmt.columns.some( (column) => column.type === "FIELD" || column.type === "WILDCARD" || column.type === "PARENT_WILDCARD" || column.type === "CASE_COL" || column.type === "AGGREGATE" && (column.func === "MIN" || column.func === "MAX" || column.func === "MODE") ); } async function inferSelectColumnMeta(stmt, outputColumns, client, cacheContext, materializedTables) { const physicalInfos = /* @__PURE__ */ new Map(); if (selectNeedsSourceColumnMeta(stmt)) { await Promise.all(physicalSelectTables(stmt).map(async (table) => { if (physicalInfos.has(table.appId)) return; const infos = await getFieldsCached(table.appId, client, cacheContext); physicalInfos.set(table.appId, new Map(infos.map((info) => [info.code, info]))); })); } const tables = [stmt.from, ...stmt.joins.map((join) => join.table)]; const resolveField2 = (ref) => { if (ref.tableAlias !== null) { if (ref.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { const info2 = physicalInfos.get(stmt.from.appId)?.get(ref.field); return info2 ? materializedMetaFromFieldInfo(info2, stmt.from.appId) : void 0; } const table = tables.find((candidate) => effectiveTableAlias(candidate) === ref.tableAlias); if (!table) return void 0; if (table.cteName !== null) return materializedTables?.get(table.cteName)?.columnMeta?.get(ref.field); const info = physicalInfos.get(table.appId)?.get(fieldCodeForTypeLookup(table, ref.field)); return info ? materializedMetaFromFieldInfo(info, table.appId) : systemColumnMeta(ref.field); } if (stmt.joins.length === 0) { if (stmt.from.cteName !== null) return materializedTables?.get(stmt.from.cteName)?.columnMeta?.get(ref.field); const info = physicalInfos.get(stmt.from.appId)?.get(fieldCodeForTypeLookup(stmt.from, ref.field)); return info ? materializedMetaFromFieldInfo(info, stmt.from.appId) : systemColumnMeta(ref.field); } const matches = tables.flatMap((table) => { if (table.cteName !== null) { const materialized = materializedTables?.get(table.cteName); if (!materialized?.columns.includes(ref.field)) return []; return [materialized.columnMeta?.get(ref.field)]; } const info = physicalInfos.get(table.appId)?.get(fieldCodeForTypeLookup(table, ref.field)); const meta3 = info ? materializedMetaFromFieldInfo(info, table.appId) : systemColumnMeta(ref.field); return meta3 ? [meta3] : []; }); return matches.length === 1 ? matches[0] : void 0; }; const inferred = /* @__PURE__ */ new Map(); const hasWildcard = stmt.columns.some((column) => column.type === "WILDCARD" || column.type === "PARENT_WILDCARD"); if (stmt.columns.length === 1 && (stmt.columns[0].type === "WILDCARD" || stmt.columns[0].type === "PARENT_WILDCARD")) { for (const output of outputColumns) { const meta3 = resolveField2(aggregateFieldRef(output)); if (meta3) inferred.set(output, meta3); } return inferred; } if (hasWildcard) { for (const output of outputColumns) { const meta3 = resolveField2(aggregateFieldRef(output)); if (meta3) inferred.set(output, meta3); } } const explicitColumns = stmt.columns.filter( (column) => column.type !== "WILDCARD" && column.type !== "PARENT_WILDCARD" ); explicitColumns.forEach((column, index) => { const output = hasWildcard ? "alias" in column && column.alias ? column.alias : void 0 : outputColumns[index]; if (!output) return; let meta3; if (column.type === "FIELD") { meta3 = resolveField2(aggregateFieldRef(column.field)); } else if (column.type === "AGGREGATE") { if (column.func === "GROUP_CONCAT") { meta3 = syntheticColumnMeta("string"); } else if (column.func === "COUNT" || column.func === "SUM" || column.func === "AVG" || column.func === "STDDEV_POP" || column.func === "STDDEV_SAMP" || column.func === "VAR_POP" || column.func === "VAR_SAMP" || column.func === "MEDIAN") { meta3 = syntheticColumnMeta("number"); } else if ((column.func === "MIN" || column.func === "MAX" || column.func === "MODE") && column.arg.type !== "WILDCARD") { meta3 = inferAggregateArgMeta(column.arg, resolveField2); } } else if (column.type === "ARITH_AGG_COL" || column.type === "ARITH_COL") { meta3 = syntheticColumnMeta("number"); } else if (column.type === "LITERAL_COL") { meta3 = syntheticColumnMeta("string"); } else if (column.type === "SCALAR_VALUE_COL") { const expr = column.expr; if (expr.type === "STRING_FUNC") meta3 = stringFunctionColumnMeta(expr); else if (expr.type === "NUMBER" || expr.type === "SCALAR_ARITH") meta3 = syntheticColumnMeta("number"); else if (expr.type === "FIELD") meta3 = resolveField2(expr); else meta3 = syntheticColumnMeta("string"); } else if (column.type === "STRFUNC_COL") { meta3 = stringFunctionColumnMeta(column.expr); } else if (column.type === "WINDOW_COL") { meta3 = syntheticColumnMeta("number"); } else if (column.type === "CASE_COL") { const results = column.expr.branches.map((branch) => caseResultColumnMeta(branch.result, resolveField2)); if (column.expr.elseResult) results.push(caseResultColumnMeta(column.expr.elseResult, resolveField2)); meta3 = mergeExpressionColumnMeta(results); } else if (column.type === "SCALAR_SUBQUERY_COL") { meta3 = unknownStringColumnMeta(); } if (meta3) inferred.set(output, meta3); }); return inferred; } function mergeUnionColumnMeta(left, right) { const leftMeta = materializedMetaBySelectResult.get(left); const rightMeta = materializedMetaBySelectResult.get(right); const merged = /* @__PURE__ */ new Map(); left.columns.forEach((column, index) => { const a = leftMeta?.get(column); const rightColumn = right.columns[index]; const b = rightColumn === void 0 ? void 0 : rightMeta?.get(rightColumn); if (a && b) merged.set(column, mergeExpressionColumnMeta([a, b])); else if (a || b) merged.set(column, unknownStringColumnMeta()); }); return merged; } function buildSelectFieldTypeResolvers(stmt, fieldTypesByApp) { const tables = [stmt.from, ...stmt.joins.map((join) => join.table)]; const physicalTables = tables.filter((table) => table.cteName === null); const outputAliases = new Set( stmt.columns.map((column) => "alias" in column ? column.alias : null).filter((alias) => alias !== null) ); const row = (field) => { if (field.tableAlias !== null) { if (field.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { return fieldTypesByApp.get(stmt.from.appId)?.get(field.field); } const table = tables.find((candidate) => effectiveTableAlias(candidate) === field.tableAlias); if (!table || table.cteName !== null) return void 0; return subtableSystemFieldType(table, field.field) ?? fieldTypesByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, field.field)); } if (stmt.joins.length === 0) { if (stmt.from.cteName !== null) return void 0; return subtableSystemFieldType(stmt.from, field.field) ?? fieldTypesByApp.get(stmt.from.appId)?.get(fieldCodeForTypeLookup(stmt.from, field.field)); } if (tables.some((table) => table.cteName !== null)) return void 0; const matches = physicalTables.flatMap((table) => { const type = subtableSystemFieldType(table, field.field) ?? fieldTypesByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, field.field)); return type ? [type] : []; }); return matches.length === 1 ? matches[0] : void 0; }; const having = (field) => { if (field.tableAlias === null && outputAliases.has(field.field)) return void 0; return row(field); }; return { row, having }; } async function executeFullScanSelect(stmt, client, options, cacheContext, cteCache, allowOriginalWherePushdown = true, preloadedOrderMeta) { const maxRecords2 = options.maxRecords ?? 1e4; const warnings = /* @__PURE__ */ new Set(); const parallel = options.fetchParallel ?? 1; await Promise.all([ resolveSubqueries(stmt.where, client, options, cacheContext, cteCache), resolveSubqueries(stmt.having, client, options, cacheContext, cteCache) ]); const [pushdownMeta, typedInFieldTypes, aggregateSortKindResolver] = await Promise.all([ loadTypedPushdownMeta(stmt, client, cacheContext), loadTypedInFieldTypes(stmt, client, cacheContext), loadAggregateSortKindResolver(stmt, client, cacheContext, cteCache) ]); const fieldTypeResolvers = buildSelectFieldTypeResolvers(stmt, typedInFieldTypes); const fieldSemanticsResolver = await buildWhereFieldSemanticsResolver( stmt, client, cacheContext, cteCache, whereNeedsFieldMetadata(stmt.having) || selectCaseConditionsNeedFieldMetadata(stmt) ); const havingFieldSemanticsResolver = buildHavingFieldSemanticsResolver(stmt, fieldSemanticsResolver); const pushdownPlan = buildKlikePushdownPlan(stmt, pushdownMeta); validateKlikePushdownPlan(pushdownPlan); const mainPushDown = pushdownPlan.mainCondition; const tableConditions = pushdownPlan.joinConditions; const constantFalse = isConstantFalseWhere(stmt.where); const mainFetch = constantFalse ? Promise.resolve([]) : fetchTableRecordsForFullScan( stmt, stmt.from, client, maxRecords2, parallel, true, options.onLimitReached ?? "error", warnings, mainPushDown, allowOriginalWherePushdown ); const parallelJoins = []; const onOptJoins = []; for (const join of stmt.joins) { if (constantFalse) { parallelJoins.push({ join, promise: Promise.resolve([]) }); continue; } const jCond = join.table.alias ? tableConditions.get(join.table.alias) ?? null : null; if (jCond !== null) { parallelJoins.push({ join, promise: fetchTableRecordsForFullScan( stmt, join.table, client, maxRecords2, parallel, false, options.onLimitReached ?? "error", warnings, jCond ) }); } else { onOptJoins.push(join); } } const scalarCachePromise = resolveScalarColumns(stmt.columns, client, options, cacheContext, cteCache); const orderByMetaPromise = preloadedOrderMeta ? Promise.resolve(preloadedOrderMeta) : buildOrderByMetaForSelect(stmt, client, cacheContext, cteCache); scalarCachePromise.catch(() => { }); orderByMetaPromise.catch(() => { }); const mainRecords = await mainFetch; const tables = /* @__PURE__ */ new Map(); tables.set(stmt.from.alias, mainRecords); for (const { join, promise: promise2 } of parallelJoins) { tables.set(join.table.alias, await promise2); } await Promise.all(onOptJoins.map(async (join) => { const optimized = await tryFetchJoinRecordsBySourceKeys( stmt, join, tables, client, maxRecords2, parallel, options.onLimitReached ?? "error", warnings, null ); const joinRecords = optimized ?? await fetchTableRecordsForFullScan( stmt, join.table, client, maxRecords2, parallel, false, options.onLimitReached ?? "error", warnings, null ); tables.set(join.table.alias, joinRecords); })); const scalarCache = await scalarCachePromise; const { optionOrders, sortKinds, semantics } = await orderByMetaPromise; const { rows, columns } = runFullScan({ tables, stmt, scalarCache, optionOrders, sortKinds, orderSemantics: semantics, fieldTypeResolver: fieldTypeResolvers.row, fieldSemanticsResolver, havingFieldTypeResolver: fieldTypeResolvers.having, havingFieldSemanticsResolver, aggregateSortKindResolver, appliedKlikes: pushdownPlan.appliedKlikes }); return { type: "SELECT", rows, columns, rowCount: rows.length, warnings: [...warnings] }; } async function executeUnion(stmt, client, options, cacheContext) { const [leftResult, rightResult] = await Promise.all([ stmt.left.type === "UNION" ? executeUnion(stmt.left, client, options, cacheContext) : executeSelect(stmt.left, client, options, cacheContext), executeSelect(stmt.right, client, options, cacheContext) ]); const leftCols = leftResult.columns; const rightCols = rightResult.columns; const remappedRight = rightResult.rows.map((row) => { const mapped = {}; leftCols.forEach((col, i) => { mapped[col] = row[rightCols[i] ?? col] ?? ""; }); return mapped; }); const combined = [...leftResult.rows, ...remappedRight]; const rows = stmt.all ? combined : deduplicateRows(combined, leftCols); return { type: "SELECT", rows, columns: leftCols, rowCount: rows.length }; } function deduplicateRows(rows, columns) { const seen = /* @__PURE__ */ new Set(); return rows.filter((row) => { const key = JSON.stringify(columns.map((c) => row[c] ?? "")); if (seen.has(key)) return false; seen.add(key); return true; }); } async function executeWith(stmt, client, options, cacheContext, seed, captureColumnMeta = false) { if ((seed == null || seed.size === 0) && canInlineSingleCte(stmt)) { return executeSelect(buildInlinedQuery(stmt), client, options, cacheContext, void 0, captureColumnMeta); } const cteCache = new Map(seed ?? []); for (const cte of stmt.ctes) { let result; if (cte.query.type === "SHOW_APPS") { result = await executeShowApps(client); } else if (cte.query.type === "DESCRIBE") { result = await executeDescribe(cte.query, client, cacheContext); } else { result = await executeQueryWithCte(cte.query, client, options, cteCache, cacheContext, true); } cteCache.set(cte.name, { rows: result.rows, columns: result.columns, columnMeta: materializedMetaBySelectResult.get(result) }); } return executeQueryWithCte(stmt.query, client, options, cteCache, cacheContext, captureColumnMeta); } async function executeQueryWithCte(query, client, options, cteCache, cacheContext, captureColumnMeta = false) { if (query.type === "UNION") { const [leftResult, rightResult] = await Promise.all([ executeQueryWithCte(query.left, client, options, cteCache, cacheContext, captureColumnMeta), executeQueryWithCte(query.right, client, options, cteCache, cacheContext, captureColumnMeta) ]); const leftCols = leftResult.columns; const rightCols = rightResult.columns; const remapped = rightResult.rows.map((row) => { const mapped = {}; leftCols.forEach((col, i) => { mapped[col] = row[rightCols[i] ?? col] ?? ""; }); return mapped; }); const combined = [...leftResult.rows, ...remapped]; const rows = query.all ? combined : deduplicateRows(combined, leftCols); const result2 = { type: "SELECT", rows, columns: leftCols, rowCount: rows.length }; if (captureColumnMeta) { materializedMetaBySelectResult.set(result2, mergeUnionColumnMeta(leftResult, rightResult)); } return result2; } const hasCteRef = query.from.cteName != null && query.from.cteName !== NO_FROM_CTE_NAME || query.joins.some((j) => j.table.cteName != null); if (!hasCteRef) { return executeSelect(query, client, options, cacheContext, cteCache, captureColumnMeta); } const result = await executeFullScanWithCte(query, client, options, cteCache, cacheContext); if (captureColumnMeta) { materializedMetaBySelectResult.set(result, await inferSelectColumnMeta(query, result.columns, client, cacheContext, cteCache)); } return result; } async function executeFullScanWithCte(stmt, client, options, cteCache, cacheContext) { const hiddenQualifiedAliases = /* @__PURE__ */ new Set(); const withEffectiveAlias = (table) => { if (table.alias !== null || table.cteName === null) return table; const alias = effectiveTableAlias(table); hiddenQualifiedAliases.add(alias); return { ...table, alias }; }; stmt = { ...stmt, from: withEffectiveAlias(stmt.from), joins: stmt.joins.map((join) => ({ ...join, table: withEffectiveAlias(join.table) })) }; const aliases = /* @__PURE__ */ new Set(); for (const table of [stmt.from, ...stmt.joins.map((join) => join.table)]) { const alias = effectiveTableAlias(table); if (alias === null) continue; if (aliases.has(alias)) { throw new Error(`ArgumentError: effective alias ${alias} is used by multiple tables.`); } aliases.add(alias); } const requireMaterializedTable = (name) => { const table = cteCache.get(name); if (!table) { throw new Error(`ArgumentError: materialized source ${name} is not available.`); } return table; }; for (const table of [stmt.from, ...stmt.joins.map((join) => join.table)]) { if (table.cteName !== null) requireMaterializedTable(table.cteName); } const maxRecords2 = options.maxRecords ?? 1e4; const warnings = /* @__PURE__ */ new Set(); const parallel = options.fetchParallel ?? 1; await Promise.all([ resolveSubqueries(stmt.where, client, options, cacheContext, cteCache), resolveSubqueries(stmt.having, client, options, cacheContext, cteCache), resolveSelectCaseSubqueries(stmt, client, options, cacheContext, cteCache) ]); const whereCapability = await resolveSelectWhereCapability(stmt, client, cacheContext, cteCache); if (whereCapability.capability === "UNSUPPORTED") { throw new Error(`ArgumentError: WHERE predicate is unsupported (${formatWhereCapabilityFailure(whereCapability)}).`); } const orderMeta = await buildOrderByMetaForSelect(stmt, client, cacheContext, cteCache); if (hasCanonicalOrder(stmt)) { (stmt.orderMode === "KINTONE_NATIVE" ? planKorder : planCanonicalOrder)({ stmt, staticMode: "FULL_SCAN", whereCapability: whereCapability.capability, orderSemantics: orderMeta.semantics, maxRecords: maxRecords2, hasKlike: whereHasKlike(stmt.where) }); } const [pushdownMeta, typedInFieldTypes, aggregateSortKindResolver] = await Promise.all([ loadTypedPushdownMeta(stmt, client, cacheContext), loadTypedInFieldTypes(stmt, client, cacheContext), loadAggregateSortKindResolver(stmt, client, cacheContext, cteCache) ]); const fieldTypeResolvers = buildSelectFieldTypeResolvers(stmt, typedInFieldTypes); const fieldSemanticsResolver = await buildWhereFieldSemanticsResolver( stmt, client, cacheContext, cteCache, whereNeedsFieldMetadata(stmt.having) || selectCaseConditionsNeedFieldMetadata(stmt) ); const havingFieldSemanticsResolver = buildHavingFieldSemanticsResolver(stmt, fieldSemanticsResolver); const pushdownPlan = buildKlikePushdownPlan(stmt, pushdownMeta); validateKlikePushdownPlan(pushdownPlan); const scalarCachePromise = resolveScalarColumns(stmt.columns, client, options, cacheContext, cteCache); const orderByMetaPromise = Promise.resolve(orderMeta); scalarCachePromise.catch(() => { }); orderByMetaPromise.catch(() => { }); const tables = /* @__PURE__ */ new Map(); const tableColumns = /* @__PURE__ */ new Map(); if (stmt.from.cteName != null) { const table = requireMaterializedTable(stmt.from.cteName); tables.set(stmt.from.alias, table.rows.map(processRowToKintoneRecord)); tableColumns.set(stmt.from.alias, table.columns); } else { const mainRecords = await fetchTableRecordsForFullScan( stmt, stmt.from, client, maxRecords2, parallel, true, options.onLimitReached ?? "error", warnings, pushdownPlan.mainCondition, whereCapability.capability === "EXACT_PUSHDOWN" ); tables.set(stmt.from.alias, mainRecords); } const joinFetches = stmt.joins.map(async (join) => { if (join.table.cteName != null) { const table = requireMaterializedTable(join.table.cteName); tables.set(join.table.alias, table.rows.map(processRowToKintoneRecord)); tableColumns.set(join.table.alias, table.columns); } else { const pushDownCond = join.table.alias ? pushdownPlan.joinConditions.get(join.table.alias) ?? null : null; const optimized = await tryFetchJoinRecordsBySourceKeys( stmt, join, tables, client, maxRecords2, parallel, options.onLimitReached ?? "error", warnings, pushDownCond ); const joinRecords = optimized ?? await fetchTableRecordsForFullScan( stmt, join.table, client, maxRecords2, parallel, false, options.onLimitReached ?? "error", warnings, pushDownCond ); tables.set(join.table.alias, joinRecords); } }); await Promise.all(joinFetches); const scalarCache = await scalarCachePromise; const { optionOrders, sortKinds, semantics } = await orderByMetaPromise; const sourceColumns = stmt.joins.length === 0 && stmt.from.cteName != null ? requireMaterializedTable(stmt.from.cteName).columns : void 0; const { rows, columns } = runFullScan({ tables, stmt, scalarCache, optionOrders, sortKinds, orderSemantics: semantics, fieldTypeResolver: fieldTypeResolvers.row, fieldSemanticsResolver, havingFieldTypeResolver: fieldTypeResolvers.having, havingFieldSemanticsResolver, aggregateSortKindResolver, appliedKlikes: pushdownPlan.appliedKlikes, sourceColumns, tableColumns, hiddenQualifiedAliases }); return { type: "SELECT", rows, columns, rowCount: rows.length, warnings: [...warnings] }; } function processRowToKintoneRecord(row) { return Object.fromEntries( Object.entries(row).map(([k, v]) => [k, { value: v ?? "" }]) ); } async function fetchTableRecordsForFullScan(stmt, table, client, maxRecords2, parallel, isMainTable, onLimit2, warnings, pushDownCond = null, allowOriginalWherePushdown = true) { const fields = selectToFetchAllFields(stmt, table); const onTruncate = (max) => { warnings.add(`\u53D6\u5F97\u4E0A\u9650\uFF08${max} \u4EF6\uFF09\u306B\u9054\u3057\u305F\u305F\u3081\u3001${max} \u4EF6\u3067\u6253\u3061\u5207\u3063\u3066\u8868\u793A\u3057\u3066\u3044\u307E\u3059\u3002`); }; if (!table.subtableCode) { const baseQuery = isMainTable && allowOriginalWherePushdown ? selectToFetchAllParams(stmt, table.appId).query : ""; const pushQuery = pushDownCond !== null ? whereToKintone(pushDownCond) : ""; const query = baseQuery && pushQuery ? `(${baseQuery}) and (${pushQuery})` : baseQuery || pushQuery; const resolved = await fetchRecordsForSharedPlan(client.getRecords, table.appId, query, fields, { parallel, maxRecords: maxRecords2, onLimit: onLimit2, onTruncate }); return resolved.records; } const parentQuery = isMainTable ? "" : ""; const parentResolved = await fetchRecordsForSharedPlan(client.getRecords, table.appId, parentQuery, fields, { parallel, maxRecords: maxRecords2, onLimit: onLimit2, onTruncate }); const parentRecords = parentResolved.records; return expandSubtableRecords(parentRecords, table.subtableCode); } var UPSERT_IN_CHUNK_SIZE = 50; function normalizeKeyPart(v) { const decimal = parseExactDecimal(v); if (decimal !== null) return JSON.stringify(decimal); return v; } function upsertCompositeKey(parts) { return JSON.stringify(parts); } function upsertNormalizedKey(parts, numericKey) { return JSON.stringify(parts.map((p, i) => numericKey[i] ? normalizeKeyPart(p) : p)); } function lookupUpsertTarget(index, keyParts) { const exact = index.raw.get(upsertCompositeKey(keyParts)); if (exact !== void 0) return exact; if (!index.numericKey.some(Boolean)) return void 0; return index.normalized.get(upsertNormalizedKey(keyParts, index.numericKey)); } async function resolveUpsertTargets(appId, keyFields, rowKeyValues, client, options, fieldTypes) { const maxRecords2 = options.maxRecords ?? 1e4; const parallel = options.fetchParallel ?? 1; const numericKey = keyFields.map((f) => fieldTypes.get(f) === "NUMBER"); const index = { raw: /* @__PURE__ */ new Map(), normalized: /* @__PURE__ */ new Map(), numericKey }; const setMax = (map2, key, id) => { const cur = map2.get(key); if (cur === void 0 || id > cur) map2.set(key, id); }; const addRecordToIndex = (parts, id) => { setMax(index.raw, upsertCompositeKey(parts), id); if (numericKey.some(Boolean)) { setMax(index.normalized, upsertNormalizedKey(parts, numericKey), id); } }; const batchFirstKeys = /* @__PURE__ */ new Set(); const perRowKeys = []; const seen = /* @__PURE__ */ new Set(); for (const parts of rowKeyValues) { const composite = upsertCompositeKey(parts); if (seen.has(composite)) continue; seen.add(composite); if (parts.some((p) => p === "")) perRowKeys.push(parts); else batchFirstKeys.add(parts[0]); } const fields = ["$id", ...keyFields]; for (const chunk3 of splitChunks([...batchFirstKeys], UPSERT_IN_CHUNK_SIZE)) { const query = `${keyFields[0]} in (${chunk3.map(sqlQuote).join(",")})`; const records = await fetchAll(client.getRecords, appId, query, fields, { maxRecords: maxRecords2, parallel }); for (const rec of records) { const id = Number(rec["$id"]?.value); if (!Number.isFinite(id)) continue; addRecordToIndex(keyFields.map((f) => toScalarText(rec[f]?.value)), id); } } for (const parts of perRowKeys) { const query = keyFields.map((f, i) => `${f} = ${sqlQuote(parts[i])}`).join(" and "); const existing = await fetchAll(client.getRecords, appId, query, ["$id"], { maxRecords: maxRecords2, parallel }); if (existing.length === 0) continue; addRecordToIndex(parts, maxRecordId(existing)); } return index; } function maxRecordId(records) { let max = Number.NEGATIVE_INFINITY; for (const r of records) { const n = Number(r["$id"]?.value); if (Number.isFinite(n) && n > max) max = n; } if (!Number.isFinite(max)) { throw new Error("\u30EC\u30B3\u30FC\u30C9\u306B\u6570\u5024\u306E $id \u304C\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002"); } return max; } function toScalarText(value) { if (typeof value === "string") return value; if (value === null || value === void 0) return ""; return String(value); } function sqlQuote(v) { return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } function splitChunks(items, size) { const out = []; for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); return out; } var JOIN_IN_CHUNK_SIZE = 50; var JOIN_IN_MAX_CHUNKS = 6; var JOIN_IN_MAX_KEYS = JOIN_IN_CHUNK_SIZE * JOIN_IN_MAX_CHUNKS; async function tryFetchJoinRecordsBySourceKeys(stmt, join, tables, client, maxRecords2, parallel, onLimit2, warnings, pushDownCond = null) { if (join.type !== "INNER") return null; if (!join.table.alias) return null; if (join.table.subtableCode) return null; const leftAlias = join.on.left.tableAlias; const rightAlias = join.on.right.tableAlias; if (!leftAlias || !rightAlias) return null; let sourceAlias; let sourceField; let joinField; if (leftAlias === join.table.alias && rightAlias !== join.table.alias) { sourceAlias = rightAlias; sourceField = join.on.right.field; joinField = join.on.left.field; } else if (rightAlias === join.table.alias && leftAlias !== join.table.alias) { sourceAlias = leftAlias; sourceField = join.on.left.field; joinField = join.on.right.field; } else { return null; } const sourceRows = tables.get(sourceAlias); if (!sourceRows) return null; const keys = /* @__PURE__ */ new Set(); for (const row of sourceRows) { const raw = row[sourceField]?.value; const txt = toScalarText(raw).trim(); if (txt.length > 0) keys.add(txt); } const values = [...keys]; if (values.length === 0) return []; if (values.length > JOIN_IN_MAX_KEYS) { warnings.add( `JOIN\u30AD\u30FC\u304C ${values.length} \u4EF6\u306E\u305F\u3081 ON \u6700\u9069\u5316\u3092\u30B9\u30AD\u30C3\u30D7\u3057\u3001JOIN\u5148\u3092\u5168\u4EF6\u53D6\u5F97\u3057\u307E\u3059\uFF08\u4E0A\u9650 ${JOIN_IN_MAX_KEYS} \u4EF6\uFF09\u3002` ); return null; } const fields = selectToFetchAllFields(stmt, join.table); const onTruncate = (max) => { warnings.add(`\u53D6\u5F97\u4E0A\u9650\uFF08${max} \u4EF6\uFF09\u306B\u9054\u3057\u305F\u305F\u3081\u3001${max} \u4EF6\u3067\u6253\u3061\u5207\u3063\u3066\u8868\u793A\u3057\u3066\u3044\u307E\u3059\u3002`); }; const chunks = splitChunks(values, JOIN_IN_CHUNK_SIZE); const merged = []; const seen = /* @__PURE__ */ new Set(); for (const chunk3 of chunks) { const inClause = `${joinField} in (${chunk3.map(sqlQuote).join(",")})`; const query = pushDownCond !== null ? `(${inClause}) and (${whereToKintone(pushDownCond)})` : inClause; const resolved = await fetchRecordsForSharedPlan(client.getRecords, join.table.appId, query, fields, { parallel, maxRecords: maxRecords2, onLimit: onLimit2, onTruncate }); for (const rec of resolved.records) { const key = `${rec["$id"]?.value ?? ""}:${JSON.stringify(rec)}`; if (seen.has(key)) continue; seen.add(key); merged.push(rec); } } return merged; } var fieldTypeCache = /* @__PURE__ */ new Map(); var optionOrderCache = /* @__PURE__ */ new Map(); var sortKindCache = /* @__PURE__ */ new Map(); var fieldInfoCache = /* @__PURE__ */ new Map(); var processStatusCache = /* @__PURE__ */ new Map(); var numberPrecisionCache = /* @__PURE__ */ new Map(); function getScopedCacheValue(root, cacheContext, appId) { return root.get(cacheContext)?.get(appId); } function setScopedCacheValue(root, cacheContext, appId, value) { let scoped = root.get(cacheContext); if (!scoped) { scoped = /* @__PURE__ */ new Map(); root.set(cacheContext, scoped); } scoped.set(appId, value); } function isSystemLikeFieldCode(code) { return code.startsWith("_") || code.startsWith("$"); } async function getFieldsCached(appId, client, cacheContext) { const cached2 = getScopedCacheValue(fieldInfoCache, cacheContext, appId); if (cached2) return cached2; const loading = client.getFields(appId); setScopedCacheValue(fieldInfoCache, cacheContext, appId, loading); return loading; } async function getNumberPrecisionCached(appId, client, cacheContext) { const cached2 = getScopedCacheValue(numberPrecisionCache, cacheContext, appId); if (cached2) return cached2; const loading = client.getNumberPrecision(appId); setScopedCacheValue(numberPrecisionCache, cacheContext, appId, loading); return loading; } async function getProcessStatusesCached(appId, client, cacheContext) { const cached2 = getScopedCacheValue(processStatusCache, cacheContext, appId); if (cached2) return cached2; const loading = client.getProcessStatuses(appId); setScopedCacheValue(processStatusCache, cacheContext, appId, loading); return loading; } async function loadProcessStatusOrder(appId, client, cacheContext) { const process4 = await getProcessStatusesCached(appId, client, cacheContext); return process4.enable && process4.states !== null ? new Map(process4.states.map((state) => [state.name, state.index])) : void 0; } async function getFieldTypeMap(appId, client, cacheContext) { const cached2 = getScopedCacheValue(fieldTypeCache, cacheContext, appId); if (cached2) return cached2; const fields = await getFieldsCached(appId, client, cacheContext); const map2 = new Map(fields.map((f) => [f.code, f.fieldType])); setScopedCacheValue(fieldTypeCache, cacheContext, appId, map2); return map2; } async function getOptionOrderMapByApp(appId, client, cacheContext) { const cached2 = getScopedCacheValue(optionOrderCache, cacheContext, appId); if (cached2) return cached2; const fields = await getFieldsCached(appId, client, cacheContext); const map2 = /* @__PURE__ */ new Map(); for (const field of fields) { if (!field.optionOrder) continue; const entries = Object.entries(field.optionOrder); if (entries.length === 0) continue; map2.set(field.code, new Map(entries)); } setScopedCacheValue(optionOrderCache, cacheContext, appId, map2); return map2; } async function getFieldOptionSetMapByApp(appId, client, cacheContext) { const optionOrders = await getOptionOrderMapByApp(appId, client, cacheContext); return new Map( [...optionOrders.entries()].map(([fieldCode, order]) => [ fieldCode, new Set(order.keys()) ]) ); } async function getSortKindMapByApp(appId, client, cacheContext) { const cached2 = getScopedCacheValue(sortKindCache, cacheContext, appId); if (cached2) return cached2; const fields = await getFieldsCached(appId, client, cacheContext); const map2 = /* @__PURE__ */ new Map(); for (const field of fields) { if (!field.sortKind) continue; map2.set(field.code, field.sortKind); } setScopedCacheValue(sortKindCache, cacheContext, appId, map2); return map2; } function orderByFieldNames(stmt) { const items = [ ...stmt.orderBy, ...stmt.columns.flatMap((column) => column.type === "WINDOW_COL" ? column.orderBy : []) ]; return [...new Set(items.flatMap( (item) => item.key.type === "FIELD_NAME" ? [item.key.name] : [] ))]; } async function buildOrderSemanticsForSelect(stmt, client, cacheContext, materializedTables) { const names = orderByFieldNames(stmt); if (names.length === 0) return /* @__PURE__ */ new Map(); const tables = [stmt.from, ...stmt.joins.map((join) => join.table)]; const ambiguousFields = /* @__PURE__ */ new Set(); const infosByApp = new Map( await Promise.all([...new Set( tables.filter((table) => table.cteName === null).map((table) => table.appId) )].map(async (appId) => { const infos = await getFieldsCached(appId, client, cacheContext); return [appId, new Map(infos.map((info) => [info.code, info]))]; })) ); const resolveField2 = (ref) => { if (ref.tableAlias !== null) { if (ref.tableAlias === "_p" && stmt.from.subtableCode && stmt.from.cteName === null) { const info2 = infosByApp.get(stmt.from.appId)?.get(ref.field); return info2 ? materializedMetaFromFieldInfo(info2, stmt.from.appId) : void 0; } const table = tables.find((candidate) => effectiveTableAlias(candidate) === ref.tableAlias); if (!table) return void 0; if (table.cteName !== null) return materializedTables?.get(table.cteName)?.columnMeta?.get(ref.field); const info = infosByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, ref.field)); return info ? materializedMetaFromFieldInfo(info, table.appId) : systemColumnMeta(ref.field); } if (stmt.joins.length === 0) { if (stmt.from.cteName !== null) return materializedTables?.get(stmt.from.cteName)?.columnMeta?.get(ref.field); const info = infosByApp.get(stmt.from.appId)?.get(fieldCodeForTypeLookup(stmt.from, ref.field)); return info ? materializedMetaFromFieldInfo(info, stmt.from.appId) : systemColumnMeta(ref.field); } const matches = tables.flatMap((table) => { if (table.cteName !== null) { const materialized = materializedTables?.get(table.cteName); const meta4 = materialized?.columns.includes(ref.field) ? materialized.columnMeta?.get(ref.field) : void 0; return meta4 ? [meta4] : []; } const info = infosByApp.get(table.appId)?.get(fieldCodeForTypeLookup(table, ref.field)); const meta3 = info ? materializedMetaFromFieldInfo(info, table.appId) : systemColumnMeta(ref.field); return meta3 ? [meta3] : []; }); if (matches.length > 1) ambiguousFields.add(ref.field); return matches.length === 1 ? matches[0] : void 0; }; const aliasSemantics = /* @__PURE__ */ new Map(); for (const column of stmt.columns) { if (!("alias" in column) || !column.alias) continue; let meta3; if (column.type === "FIELD") meta3 = resolveField2(aggregateFieldRef(column.field)); else if (column.type === "ARITH_COL" || column.type === "ARITH_AGG_COL" || column.type === "WINDOW_COL") { meta3 = syntheticColumnMeta("number"); } else if (column.type === "LITERAL_COL" || column.type === "SCALAR_VALUE_COL") meta3 = syntheticColumnMeta("string"); else if (column.type === "STRFUNC_COL") meta3 = stringFunctionColumnMeta(column.expr); else if (column.type === "SCALAR_SUBQUERY_COL") meta3 = unknownStringColumnMeta(); else if (column.type === "CASE_COL") { const candidates = column.expr.branches.map((branch) => caseResultColumnMeta(branch.result, resolveField2)); if (column.expr.elseResult) candidates.push(caseResultColumnMeta(column.expr.elseResult, resolveField2)); meta3 = mergeExpressionColumnMeta(candidates); } else if (column.type === "AGGREGATE") { if (column.func === "MIN" || column.func === "MAX" || column.func === "MODE") { if (column.arg.type !== "WILDCARD") meta3 = inferAggregateArgMeta(column.arg, resolveField2); } else { meta3 = column.func === "GROUP_CONCAT" ? syntheticColumnMeta("string") : syntheticColumnMeta("number"); } } if (meta3?.semantics) aliasSemantics.set(column.alias, meta3.semantics); } const result = /* @__PURE__ */ new Map(); for (const name of names) { const base = aliasSemantics.get(name) ?? resolveField2(aggregateFieldRef(name))?.semantics; if (!base) { const ref = aggregateFieldRef(name); if (ref.tableAlias === null && ambiguousFields.has(ref.field)) { result.set(name, resolveFieldSemantics({ fieldType: "KSQL_AMBIGUOUS" })); } continue; } let semantics = base; if (base.fieldType === "STATUS" && base.source && stmt.orderMode !== "KINTONE_NATIVE") { const process4 = await getProcessStatusesCached(base.source.appId, client, cacheContext); if (process4.enable && process4.states !== null) { semantics = { ...base, optionOrder: new Map(process4.states.map((state) => [state.name, state.index])) }; } } result.set(name, semantics); } return result; } async function buildOrderByMetaForSelect(stmt, client, cacheContext, materializedTables) { const hasWindowOrderBy = stmt.columns.some( (column) => column.type === "WINDOW_COL" && column.orderBy.length > 0 ); if (stmt.orderBy.length === 0 && !hasWindowOrderBy) { return { optionOrders: /* @__PURE__ */ new Map(), sortKinds: /* @__PURE__ */ new Map(), semantics: /* @__PURE__ */ new Map() }; } const [optionOrders, sortKinds, semantics] = await Promise.all([ buildOptionOrdersForSelect(stmt, client, cacheContext), buildSortKindsForSelect(stmt, client, cacheContext), buildOrderSemanticsForSelect(stmt, client, cacheContext, materializedTables) ]); return { optionOrders, sortKinds, semantics }; } async function buildOptionOrdersForSelect(stmt, client, cacheContext) { const optionOrders = /* @__PURE__ */ new Map(); const tables = [stmt.from, ...stmt.joins.map((j) => j.table)]; const appLoaded = /* @__PURE__ */ new Set(); for (const table of tables) { if (table.cteName != null) continue; if (appLoaded.has(table.appId)) continue; appLoaded.add(table.appId); const appMap = await getOptionOrderMapByApp(table.appId, client, cacheContext); for (const [fieldCode, orderMap] of appMap.entries()) { if (!optionOrders.has(fieldCode)) { optionOrders.set(fieldCode, orderMap); } } } for (const table of tables) { if (table.cteName != null || !table.alias) continue; const appMap = await getOptionOrderMapByApp(table.appId, client, cacheContext); for (const [fieldCode, orderMap] of appMap.entries()) { optionOrders.set(`${table.alias}.${fieldCode}`, orderMap); } } return optionOrders; } async function buildSortKindsForSelect(stmt, client, cacheContext) { const sortKinds = /* @__PURE__ */ new Map(); const tables = [stmt.from, ...stmt.joins.map((j) => j.table)]; const appLoaded = /* @__PURE__ */ new Set(); for (const table of tables) { if (table.cteName != null) continue; if (appLoaded.has(table.appId)) continue; appLoaded.add(table.appId); const appMap = await getSortKindMapByApp(table.appId, client, cacheContext); for (const [fieldCode, sortKind] of appMap.entries()) { if (!sortKinds.has(fieldCode)) { sortKinds.set(fieldCode, sortKind); } } } for (const table of tables) { if (table.cteName != null || !table.alias) continue; const appMap = await getSortKindMapByApp(table.appId, client, cacheContext); for (const [fieldCode, sortKind] of appMap.entries()) { sortKinds.set(`${table.alias}.${fieldCode}`, sortKind); } } return sortKinds; } function convertProcessRowValue(raw, dstFieldType) { if (typeof raw !== "string") return raw; const USER_TYPES4 = /* @__PURE__ */ new Set(["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"]); const ARRAY_TYPES3 = /* @__PURE__ */ new Set(["CHECK_BOX", "MULTI_SELECT"]); if (USER_TYPES4.has(dstFieldType ?? "")) { if (raw === "") return []; try { const parsed = JSON.parse(raw); if (Array.isArray(parsed) && parsed.every((v) => typeof v === "object" && "code" in v)) { return parsed.map((u) => ({ code: u.code })); } } catch { } return raw.split(",").map((c) => ({ code: c.trim() })); } if (ARRAY_TYPES3.has(dstFieldType ?? "")) { if (raw === "") return []; try { const parsed = JSON.parse(raw); if (Array.isArray(parsed)) return parsed.map(String); } catch { } return raw.split(",").map((v) => v.trim()); } return raw; } var NON_WRITABLE_FIELD_TYPES2 = /* @__PURE__ */ new Set([ "CALC", "RECORD_NUMBER", "CREATOR", "CREATED_TIME", "MODIFIER", "UPDATED_TIME", "STATUS", "STATUS_ASSIGNEE", "CATEGORY", "REFERENCE_TABLE" ]); function assertWritableTopLevelDmlFields(appId, targetFields, fieldInfos) { const infoByCode = new Map(fieldInfos.map((field) => [field.code, field])); for (const code of targetFields) { const info = infoByCode.get(code); if (!info) { throw new Error(`ArgumentError: DML target field ${code} does not exist.`); } if (info.inSubtable) { throw new Error( `ArgumentError: DML target field ${code} is inside a subtable. Use subtable DML syntax (for example, APP${appId}$\u30C6\u30FC\u30D6\u30EB).` ); } if (info.writable === false || NON_WRITABLE_FIELD_TYPES2.has(info.fieldType)) { throw new Error(`ArgumentError: DML target field ${code} is not writable (${info.fieldType}).`); } } } async function loadWritableTopLevelDmlFields(appId, targetFields, client, cacheContext) { const fieldInfos = await getFieldsCached(appId, client, cacheContext); assertWritableTopLevelDmlFields(appId, targetFields, fieldInfos); return fieldInfos; } async function loadNumberPrecisionForTargets(appId, targetFields, fieldInfos, client, cacheContext) { const infoByCode = new Map(fieldInfos.map((field) => [field.code, field])); return targetFields.some((code) => infoByCode.get(code)?.fieldType === "NUMBER") ? getNumberPrecisionCached(appId, client, cacheContext) : void 0; } function assertValidDmlRecords(records, targetFields, fieldInfos, numberPrecision) { const infoByCode = new Map(fieldInfos.map((field) => [field.code, field])); records.forEach((record2, rowIndex) => { for (const code of targetFields) { const info = infoByCode.get(code); const original = record2[code]?.value ?? ""; const result = validateAndNormalizeDmlValue(original, info, numberPrecision); if (!result.ok) { throw new Error(`DmlValidationError: ${result.code} ${result.message} (row=${rowIndex + 1}, field=${code})`); } const preserveCodes = ["USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT"].includes(info.fieldType) && Array.isArray(original) && original.every((item) => typeof item === "object" && item !== null && "code" in item); record2[code] = { value: preserveCodes ? original : result.value }; } }); } async function executeApplyInsertValidation(stmt, client, options, cacheContext, statementNumber) { const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const prepared = await prepareApplyInsert({ statement: stmt, fieldInfos, dmlMaxRows: resolveApplyGuardLimit(options.dmlMaxRows, "dmlMaxRows", DEFAULT_APPLY_MAX_ROWS), dmlMaxSubtableRows: resolveApplyGuardLimit( options.dmlMaxSubtableRows, "dmlMaxSubtableRows", DEFAULT_APPLY_MAX_SUBTABLE_ROWS ), statementNumber, loadNumberPrecision: () => getNumberPrecisionCached(stmt.appId, client, cacheContext) }); return materializePreparedApplyInsertValidation(stmt, prepared, fieldInfos); } async function executeApplyUpsertValidation(stmt, client, options, cacheContext, statementNumber) { const { fieldInfos, prepared } = await prepareApplyUpsertForExecution( stmt, client, options, cacheContext, statementNumber ); return materializePreparedApplyUpsertValidation(stmt, prepared, fieldInfos); } async function prepareApplyUpsertForExecution(stmt, client, options, cacheContext, statementNumber) { const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const fieldTypes = new Map(fieldInfos.map((field) => [field.code, field.fieldType])); const rowKeyValues = buildUpsertRowKeyValues(stmt); const seenSourceKeys = /* @__PURE__ */ new Set(); for (const parts of rowKeyValues) { const key = upsertNormalizedKey(parts, stmt.keyFields.map((field) => fieldTypes.get(field) === "NUMBER")); if (seenSourceKeys.has(key)) { throw new Error("ERR_KEY_DUP_SOURCE: UPSERT \u30BD\u30FC\u30B9\u5185\u3067\u30AD\u30FC\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059"); } seenSourceKeys.add(key); } const targetIndex = await resolveUpsertTargets( stmt.appId, stmt.keyFields, rowKeyValues, client, options, fieldTypes ); const targetIds = rowKeyValues.map((parts) => lookupUpsertTarget(targetIndex, parts)); const snapshotsById = /* @__PURE__ */ new Map(); const updateIds = [...new Set(targetIds.filter((id) => id !== void 0))]; const snapshotFields = ["$id", "$revision", ...fieldInfos.filter((field) => !field.inSubtable && field.fieldType !== "FILE").map((field) => field.code)]; for (const ids of splitChunks(updateIds, 100)) { const response = await client.getRecords({ app: stmt.appId, query: `$id in (${ids.join(",")}) limit 500`, fields: [...new Set(snapshotFields)] }); for (const snapshot of response.records) { const id = Number(snapshot["$id"]?.value); if (Number.isSafeInteger(id) && id > 0) snapshotsById.set(id, snapshot); } } const matches = targetIds.map((targetId, sourceRowIndex) => ({ sourceRowIndex, ...targetId === void 0 ? {} : { targetId, snapshot: snapshotsById.get(targetId) } })); const prepared = await prepareApplyUpsert({ statement: stmt, matches, fieldInfos, dmlMaxRows: resolveApplyGuardLimit(options.dmlMaxRows, "dmlMaxRows", DEFAULT_APPLY_MAX_ROWS), dmlMaxSubtableRows: resolveApplyGuardLimit( options.dmlMaxSubtableRows, "dmlMaxSubtableRows", DEFAULT_APPLY_MAX_SUBTABLE_ROWS ), statementNumber, loadNumberPrecision: () => getNumberPrecisionCached(stmt.appId, client, cacheContext) }); return { fieldInfos, prepared }; } async function executeApplyInsert(stmt, client, options, cacheContext) { if (options.allowApplyMutation !== true) { throw new Error("UnsupportedError: APPLY mutation requires allowApplyMutation=true"); } const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const prepared = await prepareApplyInsert({ statement: stmt, fieldInfos, dmlMaxRows: resolveApplyGuardLimit(options.dmlMaxRows, "dmlMaxRows", DEFAULT_APPLY_MAX_ROWS), dmlMaxSubtableRows: resolveApplyGuardLimit( options.dmlMaxSubtableRows, "dmlMaxSubtableRows", DEFAULT_APPLY_MAX_SUBTABLE_ROWS ), loadNumberPrecision: () => getNumberPrecisionCached(stmt.appId, client, cacheContext) }); const diagnostic2 = buildPreparedApplyInsertDiagnostic(prepared); if (options.confirm) { const ok = await options.confirm(prepared.guards.parentRows, "INSERT", { statementIndex: 0, statementCount: 1, statementType: "INSERT", targetAppId: stmt.appId, applyDetail: buildApplyConfirmDetailFromDiagnostic(diagnostic2), applyDiagnostic: diagnostic2 }); if (!ok) throw new OperationCancelledError("INSERT", prepared.guards.parentRows); } const result = await executePreparedApplyInsert(prepared, client, diagnostic2); return { ...result, diagnostic: withApplyDiagnosticProgress(diagnostic2, result) }; } async function executeApplyUpsert(stmt, client, options, cacheContext) { if (options.allowApplyMutation !== true) { throw new Error("UnsupportedError: APPLY mutation requires allowApplyMutation=true"); } const { prepared } = await prepareApplyUpsertForExecution(stmt, client, options, cacheContext, 1); const diagnostic2 = buildPreparedApplyUpsertDiagnostic(prepared); if (options.confirm) { const applyDetail = buildApplyConfirmDetailFromDiagnostic(diagnostic2); const ok = await options.confirm(prepared.guards.parentRows, "UPDATE", { statementIndex: 0, statementCount: 1, statementType: "UPSERT", targetAppId: stmt.appId, applyDetail, applyDiagnostic: diagnostic2 }); if (!ok) throw new OperationCancelledError("UPDATE", prepared.guards.parentRows); } const result = await executePreparedApplyUpsert(prepared, client, diagnostic2); return { type: "UPSERT", insertedCount: result.insertedCount, updatedCount: result.updatedCount, successfulChunks: result.successfulChunks, successfulParents: result.successfulParents, successfulInsertChunks: result.successfulInsertChunks, successfulUpdateChunks: result.successfulUpdateChunks, nonTransactional: result.nonTransactional, diagnostic: withApplyDiagnosticProgress(diagnostic2, result) }; } function mergeApplyConfirmTables(left, right) { const merged = /* @__PURE__ */ new Map(); for (const table of [...left, ...right]) { const current = merged.get(table.table); merged.set(table.table, current ? { table: table.table, patchRows: current.patchRows + table.patchRows, appendRows: current.appendRows + table.appendRows, removeRows: current.removeRows + table.removeRows } : { ...table }); } return [...merged.values()]; } function buildApplyConfirmDetailFromDiagnostic(diagnostic2, chunked = true) { const insert = diagnostic2.branches.find((branch) => branch.branch === "insert"); const update = diagnostic2.branches.find((branch) => branch.branch === "update"); const allTargets = diagnostic2.branches.flatMap((branch) => branch.targets); const tables = mergeApplyConfirmTables( insert ? applyDiagnosticTables(insert) : [], update ? applyDiagnosticTables(update) : [] ); const multiValues = mergeApplyDiagnosticMultiValues(allTargets); const parentRows = diagnostic2.branches.reduce((sum, branch) => sum + (branch.parentRows ?? 0), 0); const changedSubtableRows = allTargets.filter((target) => target.targetKind === "SUBTABLE").reduce((sum, target) => sum + (target.changedCount ?? 0), 0); const addedSubtableRows = tables.reduce((sum, table) => sum + table.appendRows, 0); const deletedRows = tables.reduce((sum, table) => sum + table.removeRows, 0); const result = { kind: diagnostic2.statementKind === "UPDATE" ? "APPLY_PATCH" : diagnostic2.statementKind === "INSERT" ? "APPLY_INSERT" : "APPLY_UPSERT", parentRows, changedSubtableRows, addedSubtableRows, tables, ...multiValues.length > 0 ? { multiValues } : {}, deletedRows, deletedParentRows: diagnostic2.branches.reduce((sum, branch) => sum + (branch.deletedParentRows ?? 0), 0), revisionRequired: diagnostic2.branches.some((branch) => branch.guards.revisionRequired), irreversible: true, retryOnRevisionConflict: false, ...chunked ? { nonTransactional: true, partialSuccessPossible: true } : {} }; if (diagnostic2.statementKind === "INSERT" && insert) { return { ...result, insertedParentRows: insert.parentRows ?? 0, initialSubtableRows: insert.targets.filter((target) => target.targetKind === "SUBTABLE").reduce((sum, target) => sum + (target.changedCount ?? 0), 0) }; } if (diagnostic2.statementKind === "UPSERT" && insert && update) { const insertTables = applyDiagnosticTables(insert); const updateTables = applyDiagnosticTables(update); return { ...result, insertedParentRows: insert.parentRows ?? 0, initialSubtableRows: insert.targets.filter((target) => target.targetKind === "SUBTABLE").reduce((sum, target) => sum + (target.changedCount ?? 0), 0), updatedParentRows: update.parentRows ?? 0, applyBranches: { insert: { parentRows: insert.parentRows ?? 0, initialSubtableRows: insertTables.reduce((sum, table) => sum + table.appendRows, 0), tables: insertTables }, update: { parentRows: update.parentRows ?? 0, changedSubtableRows: update.targets.filter((target) => target.targetKind === "SUBTABLE").reduce((sum, target) => sum + (target.changedCount ?? 0), 0), addedSubtableRows: updateTables.reduce((sum, table) => sum + table.appendRows, 0), tables: updateTables, deletedRows: updateTables.reduce((sum, table) => sum + table.removeRows, 0), deletedParentRows: update.deletedParentRows ?? 0 } } }; } return result; } function applyDiagnosticTables(branch) { return branch.targets.filter((target) => target.targetKind === "SUBTABLE").map((target) => { const appendRows = operationCount(target, "APPEND"); const removeRows = operationCount(target, "REMOVE"); return { table: target.field, patchRows: (target.changedCount ?? 0) - appendRows - removeRows, appendRows, removeRows }; }); } function operationCount(target, kind) { return target.operations.filter((operation) => operation.kind === kind).reduce((sum, operation) => sum + (operation.count ?? 0), 0); } function mergeApplyDiagnosticMultiValues(targets) { const details = /* @__PURE__ */ new Map(); for (const target of targets.filter((item) => item.targetKind === "MULTI_VALUE")) { const incoming = { field: target.field, fieldType: target.fieldType ?? "UNKNOWN", addedValues: operationCount(target, "ADD"), removedValues: operationCount(target, "REMOVE_VALUE"), changedValues: target.changedCount ?? 0, parents: (target.postImages ?? []).map((item) => ({ parentId: item.parentId, postImage: item.value })) }; const current = details.get(target.field); details.set(target.field, current ? { ...current, addedValues: current.addedValues + incoming.addedValues, removedValues: current.removedValues + incoming.removedValues, changedValues: current.changedValues + incoming.changedValues, parents: [...current.parents, ...incoming.parents] } : incoming); } return [...details.values()]; } async function executeDmlValidation(stmt, client, options, cacheContext, tempTables, statementNumber) { if (stmt.type === "INSERT" && stmt.applyBlocks?.length) { return executeApplyInsertValidation(stmt, client, options, cacheContext, statementNumber); } if (stmt.type === "UPSERT" && (stmt.onInsertApplyBlocks?.length || stmt.onUpdateApplyBlocks?.length)) { return executeApplyUpsertValidation(stmt, client, options, cacheContext, statementNumber); } if (stmt.type === "UPDATE" && stmt.applyBlocks?.length) { const result = await executeApplyPatchUpdate( stmt, client, options, cacheContext, statementNumber ); if (result.type !== "VALIDATION") { throw new Error("InternalError: APPLY VALIDATE ONLY returned a mutation result."); } return result; } return (await prepareDmlValidation(stmt, client, options, cacheContext, tempTables, statementNumber)).result; } var RejectLimitExceededError = class extends Error { constructor(message, diagnostic2) { super(`RejectLimitExceededError: ${message}`); this.diagnostic = diagnostic2; this.name = "RejectLimitExceededError"; } }; async function prepareDmlValidation(stmt, client, options, cacheContext, tempTables, statementNumber, validateMissingCreateFields = true, includePreErrors = true) { const operation = stmt.type === "UPDATE" ? "UPDATE" : stmt.type.startsWith("UPSERT") ? "UPSERT" : "INSERT"; const payloadFields = stmt.type === "UPDATE" ? ["$id", ...stmt.assignments.map((a) => a.field)] : [...stmt.fields]; if (new Set(payloadFields).size !== payloadFields.length) { throw new Error("ArgumentError: DML target fields contain duplicates."); } const targetFields = stmt.type === "UPDATE" ? stmt.assignments.map((a) => a.field) : stmt.fields; const fieldInfos = await loadWritableTopLevelDmlFields( stmt.appId, targetFields, client, cacheContext ); if (stmt.type === "UPDATE") { await assertDmlWhereCapability(stmt, client, cacheContext); } const infoByCode = new Map(fieldInfos.map((field) => [field.code, field])); let numberPrecision = await loadNumberPrecisionForTargets( stmt.appId, targetFields, fieldInfos, client, cacheContext ); const fieldIndex = buildPostImageFieldIndex(fieldInfos, payloadFields); const snapshotFields = collectDmlPrevalidationSnapshotFields(fieldIndex); const candidates = (await materializeValidationCandidates( stmt, operation, client, options, cacheContext, tempTables, infoByCode, stmt.type === "UPDATE" ? snapshotFields : void 0 )).sort((left, right) => left.rowNumber - right.rowNumber); const updateCandidates = candidates.filter((candidate) => candidate.mode === "update"); const productionUpdateLoader = stmt.type === "UPDATE" ? loadMaterializedUpdateSnapshots : stmt.type.startsWith("UPSERT") ? (input) => loadUpsertValidationSnapshots( input, client, options.maxRecords ?? 1e4 ) : void 0; const updateSnapshotLoader = options.loadUpdateModeSnapshots ?? productionUpdateLoader; const usePreparedPostImages = updateCandidates.length > 0 && updateSnapshotLoader !== void 0; const preparedPostImages = /* @__PURE__ */ new Map(); if (usePreparedPostImages) { materializeDmlUpdateModeSparseRecords(updateCandidates, targetFields, fieldInfos); const snapshots = await updateSnapshotLoader({ appId: stmt.appId, candidates: updateCandidates, fields: snapshotFields }); const postImages = /* @__PURE__ */ new Map(); for (const candidate of updateCandidates) { if (candidate.targetId === void 0) { throw new Error(`InternalError: update-mode validation candidate has no targetId (row=${candidate.rowNumber}).`); } const snapshot = snapshots.get(candidate.targetId); if (!snapshot) { throw new Error(`InternalError: update-mode snapshot is missing for record ${candidate.targetId}.`); } const postImage = buildDmlValidationPostImage(snapshot, candidate.record ?? {}); postImages.set(candidate.rowNumber, postImage); } if (numberPrecision === void 0 && [...postImages.values()].some( (record2) => postImageNeedsNumberPrecision(record2, fieldIndex) )) { numberPrecision = await getNumberPrecisionCached(stmt.appId, client, cacheContext); } for (const candidate of updateCandidates) { const postImage = postImages.get(candidate.rowNumber); if (!postImage) throw new Error(`InternalError: validation post-image is missing for row ${candidate.rowNumber}.`); preparedPostImages.set(candidate.rowNumber, validatePostImage( postImage, fieldIndex, numberPrecision, statementNumber, candidate.rowNumber, operation )); } } const candidateValidation = validateDmlCandidates( candidates, operation, payloadFields, targetFields, fieldInfos, statementNumber, numberPrecision, stmt.checkGroups ?? [], validateMissingCreateFields, includePreErrors, { validateUpdateBuiltIns: !usePreparedPostImages } ); let { errors, invalidRows, invalidRowNumbers } = candidateValidation; if (usePreparedPostImages) { const detailsByRow = new Map(candidateValidation.candidateResults.map((detail) => [detail.rowNumber, detail])); errors = []; invalidRowNumbers = /* @__PURE__ */ new Set(); for (const candidate of candidates) { const detail = detailsByRow.get(candidate.rowNumber); if (!detail) throw new Error(`InternalError: validation detail is missing for row ${candidate.rowNumber}.`); if (candidate.mode === "create") { const candidateErrors = [...detail.preErrors, ...detail.builtInErrors, ...detail.checkErrors]; errors.push(...candidateErrors); if (candidateErrors.length > 0) invalidRowNumbers.add(candidate.rowNumber); continue; } const postImageValidation = preparedPostImages.get(candidate.rowNumber); if (!postImageValidation) { throw new Error(`InternalError: prepared post-image validation is missing for row ${candidate.rowNumber}.`); } const merged = mergeDmlCandidateValidation({ rowNumber: candidate.rowNumber, setFields: targetFields, normalizedPostImage: postImageValidation.normalizedRecord, preErrors: detail.preErrors, postImageErrors: postImageValidation.errors, checkErrors: detail.checkErrors }); candidate.record = merged.writeRecord; errors.push(...merged.errors); for (const rowNumber of merged.invalidRowNumbers) invalidRowNumbers.add(rowNumber); } invalidRows = invalidRowNumbers.size; } const columns = [...payloadFields, ...VALIDATION_META_COLUMNS]; const result = { type: "VALIDATION", operation, validatedRows: candidates.length, validRows: candidates.length - invalidRows, invalidRows, errorCount: errors.length, columns, errors, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : stmt.onErrorSkip && stmt.errorTable ? { errTable: stmt.errorTable } : {} }; const columnMeta = /* @__PURE__ */ new Map(); for (const column of payloadFields) { if (column === "$id") { columnMeta.set(column, { sortKind: "number", fieldType: "RECORD_NUMBER", semantics: resolveFieldSemantics({ fieldType: "RECORD_NUMBER" }) }); continue; } const info = infoByCode.get(column); if (info) columnMeta.set(column, materializedMetaFromFieldInfo(info, stmt.appId)); } const numericValidationMeta = /* @__PURE__ */ new Set(["$err_statement", "$err_row"]); for (const column of VALIDATION_META_COLUMNS) { columnMeta.set(column, syntheticColumnMeta(numericValidationMeta.has(column) ? "number" : "string")); } materializedMetaByValidationResult.set(result, columnMeta); return { result, candidates, invalidRowNumbers, columnMeta }; } async function executeOnErrorSkip(stmt, client, options, cacheContext, tempTables, statementNumber) { const prepared = await prepareDmlValidation( stmt, client, options, cacheContext, tempTables, statementNumber ); const errTable = stmt.errorTable; if (!errTable) throw new Error("ArgumentError: ON ERROR SKIP requires INTO #error_table."); appendValidationErrors( tempTables, errTable, prepared.result.columns, prepared.result.errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, prepared.columnMeta ); const rejectLimit = stmt.rejectLimit ?? null; if (rejectLimit !== null && prepared.result.invalidRows > rejectLimit) { throw new RejectLimitExceededError( `rejected rows (${prepared.result.invalidRows}) exceed REJECT LIMIT (${rejectLimit}).`, prepared.result ); } const valid = prepared.candidates.filter((candidate) => !prepared.invalidRowNumbers.has(candidate.rowNumber)); if (options.confirm) { const operation = stmt.type.startsWith("INSERT") ? "INSERT" : "UPDATE"; const ok = await options.confirm(valid.length, operation); if (!ok) throw new OperationCancelledError(operation, valid.length); } const common = { affectedRows: valid.length, skippedRows: prepared.result.invalidRows, rejectLimit, errTable }; if (stmt.type === "INSERT" || stmt.type === "INSERT_SELECT") { const createdIds = []; for (let i = 0; i < valid.length; i += 100) { const response = await client.postRecords({ app: stmt.appId, records: valid.slice(i, i + 100).map((c) => c.record) }); createdIds.push(response.ids); } return { type: "INSERT", createdIds, insertedCount: createdIds.flat().length, ...common }; } if (stmt.type === "UPDATE") { const updates2 = valid.map((candidate) => { if (candidate.targetId === void 0) throw new Error("InternalError: prepared UPDATE candidate has no targetId."); return { id: candidate.targetId, record: candidate.record }; }); for (let i = 0; i < updates2.length; i += 100) { await client.putRecords({ app: stmt.appId, records: updates2.slice(i, i + 100) }); } return { type: "UPDATE", updatedCount: updates2.length, ...common }; } const inserts = valid.filter((candidate) => candidate.mode === "create"); const updates = valid.filter((candidate) => candidate.mode === "update").map((candidate) => { if (candidate.targetId === void 0) throw new Error("InternalError: prepared UPSERT candidate has no targetId."); return { id: candidate.targetId, record: candidate.record }; }); let insertedCount = 0; for (let i = 0; i < inserts.length; i += 100) { const response = await client.postRecords({ app: stmt.appId, records: inserts.slice(i, i + 100).map((c) => c.record) }); insertedCount += response.ids.length; } for (let i = 0; i < updates.length; i += 100) { await client.putRecords({ app: stmt.appId, records: updates.slice(i, i + 100) }); } return { type: "UPSERT", insertedCount, updatedCount: updates.length, ...common }; } async function materializeValidationCandidates(stmt, operation, client, options, cacheContext, tempTables, infoByCode, updateSnapshotFields) { if (stmt.type === "UPDATE") { return materializeUpdateValidationCandidates( stmt, client, options, cacheContext, tempTables, updateSnapshotFields ); } let rows; let sourceRows; let sourcePresence; let sourceRowErrors; let evaluationTypes; if (stmt.type === "INSERT" || stmt.type === "UPSERT") { assertInsertCheckRefs(stmt, stmt.fields); evaluationTypes = new Map(stmt.fields.map((field) => [field, infoByCode.get(field)?.fieldType ?? ""])); assertCheckComparisonTypes(stmt, evaluationTypes); rows = stmt.values.map((row) => row.map( (value, i) => value.type === "CASE_VALUE" ? evalCaseWhenValue(value.expr, {}, infoByCode.get(stmt.fields[i])?.fieldType) : value )); } else { const selectResult = await dmlSourceMaterializer.materialize(stmt, client, options, cacheContext, tempTables, [...infoByCode.values()]); const hasChecks = (stmt.checkGroups?.length ?? 0) > 0; if (selectResult.columns.length < stmt.fields.length || !hasChecks && selectResult.columns.length !== stmt.fields.length) { throw new Error(`SELECT \u306E\u5217\u6570\uFF08${selectResult.columns.length}\uFF09\u3068 DML \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u6570\uFF08${stmt.fields.length}\uFF09\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093`); } if (hasChecks && new Set(selectResult.columns).size !== selectResult.columns.length) { throw customCheckParseError("CHECK \u4ED8\u304D DML \u30BD\u30FC\u30B9 SELECT \u306E\u51FA\u529B\u540D\u306F\u4E00\u610F\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"); } assertInsertCheckRefs(stmt, selectResult.columns); sourceRows = selectResult.rows; sourcePresence = selectResult.importPresence; sourceRowErrors = selectResult.importRowErrors; const meta3 = selectResult.columnMeta; evaluationTypes = new Map(selectResult.columns.map((column) => { const columnMeta = meta3?.get(column); const type = columnMeta?.fieldType ?? (columnMeta?.semantics?.compareMode === "number" || columnMeta?.sortKind === "number" ? "NUMBER" : "SINGLE_LINE_TEXT"); return [column, type]; })); assertCheckComparisonTypes(stmt, evaluationTypes); rows = selectResult.rows.map((row) => selectResult.columns.map((column) => row[column] ?? "")); } const candidates = rows.map((values, index) => ({ rowNumber: index + 1, operation, mode: "create", payload: new Map(stmt.fields.flatMap( (field, i) => sourcePresence && !sourcePresence[index]?.has(field) ? [] : [[field, values[i]]] )), preErrors: [...sourceRowErrors?.[index] ?? []], record: {}, evaluationRow: sourceRows?.[index] ?? Object.fromEntries( stmt.fields.map((field, i) => [field, renderValidationValue(values[i])]) ), evaluationFieldTypes: evaluationTypes })); if (stmt.type !== "UPSERT" && stmt.type !== "UPSERT_SELECT") return candidates; for (const key of stmt.keyFields) { if (!stmt.fields.includes(key)) throw new Error(`ON DUPLICATE \u306E\u30AD\u30FC\u300C${key}\u300D\u304C UPSERT \u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093`); } const fieldTypes = new Map([...infoByCode].map(([code, info]) => [code, info.fieldType])); const rowKeys = candidates.map((candidate) => stmt.keyFields.map((key) => renderValidationValue(candidate.payload.get(key)))); const numeric = stmt.keyFields.map((key) => fieldTypes.get(key) === "NUMBER"); const keyCounts = /* @__PURE__ */ new Map(); for (const parts of rowKeys) { const key = upsertNormalizedKey(parts, numeric); keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1); } const isImport = importSourceByDmlStatement.has(stmt); if (isImport && [...keyCounts.values()].some((count) => count > 1)) { throw new Error("ERR_KEY_DUP_SOURCE: UPSERT \u30BD\u30FC\u30B9\u5185\u3067\u30AD\u30FC\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059"); } const targets = await resolveUpsertTargets(stmt.appId, stmt.keyFields, rowKeys, client, options, fieldTypes); candidates.forEach((candidate, index) => { const parts = rowKeys[index]; const targetId = lookupUpsertTarget(targets, parts); candidate.mode = targetId === void 0 ? "create" : "update"; if (targetId !== void 0) candidate.targetId = targetId; stmt.keyFields.forEach((key, keyIndex) => { if (parts[keyIndex] === "") candidate.preErrors.push({ field: key, code: "ERR_KEY_EMPTY", message: `UPSERT \u30AD\u30FC ${key} \u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093` }); }); if (!isImport && (keyCounts.get(upsertNormalizedKey(parts, numeric)) ?? 0) > 1) { candidate.preErrors.push({ field: stmt.keyFields[0], code: "ERR_KEY_DUP_SOURCE", message: "UPSERT \u30BD\u30FC\u30B9\u5185\u3067\u30AD\u30FC\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059" }); } }); return candidates; } function checkRefs(stmt) { return stmt.checkGroups ? collectCheckFieldRefs(stmt.checkGroups) : []; } function assertInsertCheckRefs(stmt, available) { const names = new Set(available); for (const ref of checkRefs(stmt)) { if (ref.tableAlias !== null) { throw customCheckParseError(`CHECK \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.tableAlias}.${ref.field} \u306F\u3053\u306E\u8A55\u4FA1\u884C\u3067\u306F\u4FEE\u98FE\u3067\u304D\u307E\u305B\u3093`); } if (!names.has(ref.field)) { throw customCheckParseError(`CHECK \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F\u8A55\u4FA1\u884C\u306B\u5B58\u5728\u3057\u307E\u305B\u3093`); } } } var CHECK_UNSUPPORTED_COMPARISON_TYPES = /* @__PURE__ */ new Set([ "CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT", "FILE", "KSQL_ARRAY" ]); function assertCheckComparisonTypes(stmt, types) { if (!stmt.checkGroups) return; for (const ref of collectCheckComparisonFieldRefs(stmt.checkGroups)) { const key = ref.tableAlias ? `${ref.tableAlias}.${ref.field}` : ref.field; const type = types.get(key) ?? types.get(ref.field); if (CHECK_UNSUPPORTED_COMPARISON_TYPES.has(type ?? "")) { throw customCheckParseError(`CHECK \u306E\u6BD4\u8F03\u3067\u306F ${type} \u30D5\u30A3\u30FC\u30EB\u30C9 ${key} \u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093`); } } } async function materializeUpdateValidationCandidates(stmt, client, options, cacheContext, tempTables, snapshotFields) { if (stmt.from) { return materializeUpdateFromValidationCandidates( stmt, stmt.from, client, options, cacheContext, tempTables, snapshotFields ); } await resolveSetSubqueries(stmt.assignments, client, options, cacheContext); const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const checkTargetFields = assertUpdateCheckRefs(stmt, fieldTypes); assertCheckComparisonTypes(stmt, updateEvaluationTypes(fieldTypes, stmt.appId)); let records; let evaluationById = /* @__PURE__ */ new Map(); let snapshotsById = /* @__PURE__ */ new Map(); if (hasRowDependentAssignment(stmt)) { const getParams = updateToGetQueryForArith(stmt); const fields = [.../* @__PURE__ */ new Set([...getParams.fields, ...checkTargetFields, ...snapshotFields ?? []])]; const resolved = await fetchRecordsForSharedPlan(client.getRecords, getParams.app, getParams.query, fields, { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" }); snapshotsById = indexDmlUpdateSnapshots(resolved.records); evaluationById = snapshotsById; records = updateToPutBatchesArith(stmt, resolved.records, fieldTypes).flatMap((batch) => batch.records); } else { const getParams = updateToGetQuery(stmt); if (checkTargetFields.length > 0) { const fields = [.../* @__PURE__ */ new Set(["$id", ...checkTargetFields, ...snapshotFields ?? []])]; const resolved = await fetchRecordsForSharedPlan(client.getRecords, getParams.app, getParams.query, fields, { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" }); snapshotsById = indexDmlUpdateSnapshots(resolved.records); evaluationById = snapshotsById; records = updateToPutBatches(stmt, [...evaluationById.keys()], fieldTypes).flatMap((batch) => batch.records); } else { if (snapshotFields) { const resolved = await fetchRecordsForSharedPlan( client.getRecords, getParams.app, getParams.query, [...snapshotFields], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" } ); snapshotsById = indexDmlUpdateSnapshots(resolved.records); records = updateToPutBatches(stmt, [...snapshotsById.keys()], fieldTypes).flatMap((batch) => batch.records); } else { const resolved = await resolveDmlTargetIds(client.getRecords, getParams.app, getParams.query, { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }); records = updateToPutBatches(stmt, resolved.ids, fieldTypes).flatMap((batch) => batch.records); } } } return records.sort((a, b) => a.id - b.id).map((entry, index) => ({ rowNumber: index + 1, operation: "UPDATE", mode: "update", payload: new Map([["$id", String(entry.id)], ...stmt.assignments.map((a) => [a.field, entry.record[a.field]?.value ?? ""])]), preErrors: [], record: entry.record, targetId: entry.id, validationSnapshot: snapshotsById.get(entry.id), evaluationRow: updateEvaluationRow(evaluationById.get(entry.id), stmt.appId), evaluationFieldTypes: updateEvaluationTypes(fieldTypes, stmt.appId) })); } function indexDmlUpdateSnapshots(records) { const snapshots = /* @__PURE__ */ new Map(); for (const record2 of records) { const rawId = record2["$id"]?.value; const id = Number(rawId); if (!Number.isSafeInteger(id) || id <= 0) { throw new Error(`InternalError: invalid $id in UPDATE validation snapshot: ${String(rawId)}.`); } if (snapshots.has(id)) { throw new Error(`InternalError: duplicate $id in UPDATE validation snapshot: ${id}.`); } snapshots.set(id, record2); } return snapshots; } async function loadMaterializedUpdateSnapshots(input) { const snapshots = /* @__PURE__ */ new Map(); for (const candidate of input.candidates) { if (candidate.targetId === void 0 || !candidate.validationSnapshot) { throw new Error( `InternalError: update-mode snapshot is missing for record ${String(candidate.targetId)}.` ); } if (snapshots.has(candidate.targetId)) { throw new Error(`InternalError: duplicate UPDATE validation candidate target: ${candidate.targetId}.`); } snapshots.set(candidate.targetId, candidate.validationSnapshot); } return snapshots; } async function loadUpsertValidationSnapshots(input, client, maxRecords2) { const updateIds = [...new Set(input.candidates.map((candidate) => { const id = candidate.targetId; if (!Number.isSafeInteger(id) || id === void 0 || id <= 0) { throw new Error( `InternalError: invalid targetId in UPSERT validation candidate: ${String(id)}.` ); } return id; }))]; if (updateIds.length > maxRecords2) { throw new FetchAllLimitError( `\u53D6\u5F97\u4EF6\u6570\u304C\u4E0A\u9650\uFF08${maxRecords2} \u4EF6\uFF09\u3092\u8D85\u3048\u307E\u3057\u305F\u3002WHERE \u53E5\u3067\u7D5E\u308A\u8FBC\u3080\u304B\u3001maxRecords \u3092\u5F15\u304D\u4E0A\u3052\u3066\u304F\u3060\u3055\u3044\u3002` ); } const requestedIds = new Set(updateIds); const snapshots = /* @__PURE__ */ new Map(); for (const ids of splitChunks(updateIds, 100)) { const response = await client.getRecords({ app: input.appId, query: `$id in (${ids.join(",")}) limit 500`, fields: [...new Set(input.fields)] }); for (const snapshot of response.records) { const rawId = snapshot["$id"]?.value; const id = Number(rawId); if (!Number.isSafeInteger(id) || id <= 0) { throw new Error(`InternalError: invalid $id in UPSERT validation snapshot: ${String(rawId)}.`); } if (!requestedIds.has(id)) { throw new Error(`InternalError: unexpected $id in UPSERT validation snapshot: ${id}.`); } if (snapshots.has(id)) { throw new Error(`InternalError: duplicate $id in UPSERT validation snapshot: ${id}.`); } snapshots.set(id, snapshot); } } for (const id of updateIds) { if (!snapshots.has(id)) { throw new Error(`InternalError: update-mode snapshot is missing for record ${id}.`); } } return snapshots; } function assertUpdateCheckRefs(stmt, targetTypes) { if (stmt.from) return []; const fields = /* @__PURE__ */ new Set(); for (const ref of checkRefs(stmt)) { if (ref.tableAlias !== null && ref.tableAlias.toLowerCase() !== `app${stmt.appId}`.toLowerCase()) { throw customCheckParseError(`CHECK \u306E\u4FEE\u98FE\u5B50 ${ref.tableAlias} \u306F\u66F4\u65B0\u5148 APP${stmt.appId} \u3067\u306F\u3042\u308A\u307E\u305B\u3093`); } if (ref.field !== "$id" && !targetTypes.has(ref.field)) { throw customCheckParseError(`CHECK \u306E\u30BF\u30FC\u30B2\u30C3\u30C8\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F\u5B58\u5728\u3057\u307E\u305B\u3093`); } fields.add(ref.field); } return [...fields]; } function updateEvaluationRow(record2, appId) { if (!record2) return {}; const plain = flatten(record2, null); return Object.fromEntries([ ...Object.entries(plain), ...Object.entries(plain).map(([field, value]) => [`APP${appId}.${field}`, value]) ]); } function updateEvaluationTypes(types, appId) { return new Map([ ...types, ...[...types].map(([field, type]) => [`APP${appId}.${field}`, type]), ["$id", "RECORD_NUMBER"], [`APP${appId}.$id`, "RECORD_NUMBER"] ]); } async function materializeUpdateFromValidationCandidates(stmt, from, client, options, cacheContext, tempTables, snapshotFields) { const scope = await resolveUpdateFromCheckScope(stmt, from, client, cacheContext, tempTables); assertCheckComparisonTypes(stmt, scope.evaluationTypes); const matched = await resolveUpdateFromMatchedRecords( stmt, from, client, options, cacheContext, tempTables, snapshotFields ); const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const records = updateFromToPutBatches(stmt, matched, fieldTypes).flatMap((batch) => batch.records); const matchedById = new Map(matched.map((pair) => [Number(pair.target["$id"]?.value), pair])); const snapshotsById = snapshotFields ? indexDmlUpdateSnapshots(matched.map((pair) => pair.target)) : /* @__PURE__ */ new Map(); return records.sort((a, b) => a.id - b.id).map((entry, index) => ({ rowNumber: index + 1, operation: "UPDATE", mode: "update", payload: new Map([["$id", String(entry.id)], ...stmt.assignments.map((a) => [a.field, entry.record[a.field]?.value ?? ""])]), preErrors: [], record: entry.record, targetId: entry.id, validationSnapshot: snapshotsById.get(entry.id), evaluationRow: updateFromEvaluationRow(matchedById.get(entry.id), stmt.appId, from.alias), evaluationFieldTypes: scope.evaluationTypes })); } var UPDATE_FROM_KEY_CHUNK_SIZE = UPSERT_IN_CHUNK_SIZE; var UPDATE_FROM_UNSUPPORTED_SOURCE_TYPES = /* @__PURE__ */ new Set([ "CHECK_BOX", "MULTI_SELECT", "USER_SELECT", "ORGANIZATION_SELECT", "GROUP_SELECT", "FILE" ]); async function resolveUpdateFromMatchedRecords(stmt, from, client, options, cacheContext, tempTables, snapshotFields) { const joinKind = await resolveUpdateFromTargetJoinKind(stmt, from, client, cacheContext); const checkScope = await resolveUpdateFromCheckScope(stmt, from, client, cacheContext, tempTables); const sourceFields = [...new Set(stmt.assignments.filter((a) => a.value.type === "SOURCE_FIELD").map((a) => a.value.type === "SOURCE_FIELD" ? a.value.field : "").concat(checkScope.sourceFields))]; const requiredSourceFields = [.../* @__PURE__ */ new Set([from.joinKeyField, ...sourceFields])]; const sourceRows = await loadUpdateFromSourceRows( from, requiredSourceFields, sourceFields, client, options, cacheContext, tempTables ); const sourceByKey = /* @__PURE__ */ new Map(); const sourceQueryByKey = /* @__PURE__ */ new Map(); for (const row of sourceRows) { if (!Object.prototype.hasOwnProperty.call(row, from.joinKeyField)) { throw new Error(`ArgumentError: UPDATE ... FROM source column ${from.joinKeyField} does not exist.`); } const key = normalizeUpdateFromJoinKey(row[from.joinKeyField], joinKind, "source"); if (sourceByKey.has(key)) { throw new Error(`ArgumentError: UPDATE ... FROM source has multiple rows for normalized key ${key}.`); } sourceByKey.set(key, row); sourceQueryByKey.set(key, String(row[from.joinKeyField]).trim()); } if (sourceByKey.size === 0) return []; const maxRecords2 = options.maxRecords ?? 1e4; const targetFields = [.../* @__PURE__ */ new Set([ ...collectUpdateFromTargetFields(stmt), ...checkScope.targetFields, ...snapshotFields ?? [] ])]; const filterQuery = from.targetFilter === null ? "" : updateToGetQuery({ ...stmt, from: null, where: from.targetFilter, checkGroups: void 0 }).query; const targetRecords = []; const seenTargetIds = /* @__PURE__ */ new Set(); let fetchedTargetCount = 0; for (const keys of splitChunks([...sourceQueryByKey.values()], UPDATE_FROM_KEY_CHUNK_SIZE)) { const keyQuery = `${from.targetJoinField} in (${keys.map(sqlQuote).join(",")})`; const query = filterQuery ? `(${keyQuery}) and (${filterQuery})` : keyQuery; const resolved = await fetchRecordsForSharedPlan( client.getRecords, stmt.appId, query, targetFields, { maxRecords: maxRecords2, parallel: options.fetchParallel ?? 1, onLimit: "error" } ); fetchedTargetCount += resolved.records.length; if (fetchedTargetCount > maxRecords2) { throw new FetchAllLimitError( `\u53D6\u5F97\u4EF6\u6570\u304C\u4E0A\u9650\uFF08${maxRecords2} \u4EF6\uFF09\u3092\u8D85\u3048\u307E\u3057\u305F\u3002WHERE \u53E5\u3067\u7D5E\u308A\u8FBC\u3080\u304B\u3001maxRecords \u3092\u5F15\u304D\u4E0A\u3052\u3066\u304F\u3060\u3055\u3044\u3002` ); } for (const record2 of resolved.records) { const id = record2["$id"]?.value; if (typeof id !== "string" || id === "") { throw new Error("ArgumentError: UPDATE ... FROM target record does not contain a valid $id."); } if (seenTargetIds.has(id)) continue; seenTargetIds.add(id); targetRecords.push(record2); } } const matched = []; for (const target of targetRecords) { const raw = target[from.targetJoinField]?.value; const key = normalizeUpdateFromJoinKey(raw, joinKind, "target"); if (key === null) continue; const source = sourceByKey.get(key); if (source !== void 0) matched.push({ target, source }); } return matched; } async function resolveUpdateFromTargetJoinKind(stmt, from, client, cacheContext) { if (from.targetJoinField === "$id") return "id"; const info = (await getFieldsCached(stmt.appId, client, cacheContext)).find((field) => field.code === from.targetJoinField); if (!info) { throw new Error(`ArgumentError: UPDATE ... FROM target column ${from.targetJoinField} does not exist.`); } if (info.inSubtable || info.writable === false || info.fieldType !== "SINGLE_LINE_TEXT" && info.fieldType !== "NUMBER") { throw new Error( `ArgumentError: UPDATE ... FROM does not support target join field type ${info.fieldType} (${from.targetJoinField}).` ); } return info.fieldType === "NUMBER" ? "number" : "string"; } async function loadUpdateFromSourceRows(from, requiredSourceFields, sourceValueFields, client, options, cacheContext, tempTables) { if (from.cteName !== null) { const table = tempTables?.get(from.cteName); if (!table) throw new Error(`ArgumentError: temp table ${from.cteName} is not available.`); for (const field of requiredSourceFields) { if (!table.columns.includes(field)) { throw new Error(`ArgumentError: UPDATE ... FROM source column ${field} does not exist.`); } } return table.rows; } const sourceTypes = await getFieldTypeMap(from.appId, client, cacheContext); const joinType = from.joinKeyField === "$id" ? "RECORD_NUMBER" : sourceTypes.get(from.joinKeyField); if (joinType === void 0) { throw new Error(`ArgumentError: UPDATE ... FROM source column ${from.joinKeyField} does not exist.`); } if (from.joinKeyField !== "$id" && joinType !== "SINGLE_LINE_TEXT" && joinType !== "NUMBER") { throw new Error( `ArgumentError: UPDATE ... FROM does not support source join field type ${joinType} (${from.joinKeyField}).` ); } for (const field of sourceValueFields) { if (field !== "$id" && !sourceTypes.has(field)) { throw new Error(`ArgumentError: UPDATE ... FROM source column ${field} does not exist.`); } const type = field === "$id" ? "RECORD_NUMBER" : sourceTypes.get(field); if (UPDATE_FROM_UNSUPPORTED_SOURCE_TYPES.has(type ?? "")) { throw new Error(`ArgumentError: UPDATE ... FROM does not support source field type ${type} (${field}).`); } } const resolved = await fetchRecordsForSharedPlan( client.getRecords, from.appId, "", requiredSourceFields, { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" } ); return resolved.records.map((record2) => flatten(record2, null)); } function normalizeUpdateFromJoinKey(raw, kind, side) { if (typeof raw !== "string") { throw new Error(`ArgumentError: UPDATE ... FROM ${side} key must be a scalar string: ${String(raw)}`); } if (kind === "string") { if (raw === "") { if (side === "target") return null; throw new Error("ArgumentError: UPDATE ... FROM source key must not be empty."); } return raw; } if (kind === "number" && side === "target" && raw === "") return null; if (kind === "id") { const text = raw.trim(); const id = Number(text); if (text === "" || !Number.isSafeInteger(id) || id <= 0) { throw new Error(`ArgumentError: UPDATE ... FROM ${side} key must be a positive safe integer: ${raw}`); } return String(id); } const decimal = parseExactDecimal(raw); if (decimal === null) { throw new Error(`ArgumentError: UPDATE ... FROM ${side} key must be a finite decimal: ${raw}`); } return JSON.stringify(decimal); } async function executeCheckedPlainDml(stmt, client, options, cacheContext, tempTables) { const prepared = await prepareDmlValidation( stmt, client, options, cacheContext, tempTables, 1, false, false ); if (prepared.result.errors.length > 0) { const first = prepared.result.errors[0]; throw new Error( `DmlValidationError: ${first["$err_code"]} ${first["$err_message"]} (row=${first["$err_row"]}, field=${first["$err_field"]})` ); } const candidates = prepared.candidates; const confirmOperation = stmt.type.startsWith("INSERT") ? "INSERT" : "UPDATE"; if (options.confirm && candidates.length > 0) { const ok = await options.confirm(candidates.length, confirmOperation); if (!ok) throw new OperationCancelledError(confirmOperation, candidates.length); } if (stmt.type === "INSERT" || stmt.type === "INSERT_SELECT") { const createdIds = []; for (let i = 0; i < candidates.length; i += 100) { const response = await client.postRecords({ app: stmt.appId, records: candidates.slice(i, i + 100).map((c) => c.record) }); createdIds.push(response.ids); } return { type: "INSERT", createdIds, insertedCount: createdIds.flat().length }; } if (stmt.type === "UPDATE") { const updates2 = candidates.map((candidate) => ({ id: candidate.targetId, record: candidate.record })); for (let i = 0; i < updates2.length; i += 100) await client.putRecords({ app: stmt.appId, records: updates2.slice(i, i + 100) }); return { type: "UPDATE", updatedCount: updates2.length }; } const inserts = candidates.filter((candidate) => candidate.mode === "create"); const updates = candidates.filter((candidate) => candidate.mode === "update").map((candidate) => ({ id: candidate.targetId, record: candidate.record })); let insertedCount = 0; for (let i = 0; i < inserts.length; i += 100) { const response = await client.postRecords({ app: stmt.appId, records: inserts.slice(i, i + 100).map((c) => c.record) }); insertedCount += response.ids.length; } for (let i = 0; i < updates.length; i += 100) await client.putRecords({ app: stmt.appId, records: updates.slice(i, i + 100) }); return { type: "UPSERT", insertedCount, updatedCount: updates.length }; } async function executeInsert(stmt, client, options, cacheContext) { if (stmt.applyBlocks?.length) return executeApplyInsert(stmt, client, options, cacheContext); if (stmt.checkGroups?.length) return executeCheckedPlainDml(stmt, client, options, cacheContext); if (stmt.subtableCode) { return executeInsertSubtable(stmt, client, options, cacheContext); } const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext); const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const batches = insertToPostBatches(stmt, fieldTypes); assertValidDmlRecords(batches.flatMap((batch) => batch.records), stmt.fields, fieldInfos, numberPrecision); const createdIds = []; for (const batch of batches) { const res = await client.postRecords(batch); createdIds.push(res.ids); } return { type: "INSERT", createdIds, insertedCount: createdIds.flat().length }; } function importPlaceholderSelect() { return { type: "SELECT", distinct: false, columns: [], from: { appId: 0, alias: null, cteName: NO_FROM_CTE_NAME }, joins: [], where: null, groupBy: [], having: null, orderMode: "CANONICAL", orderBy: [], limit: null, offset: null }; } async function executeImport(stmt, client, options, cacheContext, tempTables) { if (!options.enableImport) throw new Error("UnsupportedError: IMPORT capability is disabled."); const handle = resolveImportSource(stmt.source.sourceName, options.importSource); if (stmt.targets?.some((target) => target.kind === "SUBTABLE")) { if (!stmt.validateOnly && !options.supportsImportConfirmDetail) { throw new Error("UnsupportedError: IMPORT subtable mutation requires a surface that displays parent/table replacement and deletion detail; use VALIDATE ONLY/EXPLAIN."); } if (stmt.source.kind === "CSV") { if (stmt.writeMode !== "UPDATE_RECORD_NUMBER" || !stmt.recordNumberSourceHeader) throw new Error("ArgumentError: CSV subtable replacement requires IMPORT UPDATE and MATCH RECORD NUMBER SOURCE."); if (!stmt.replaceSubtables?.length) throw new Error("ArgumentError: CSV subtable replacement requires REPLACE SUBTABLES (...)."); const declared = new Set(stmt.targets.filter((target) => target.kind === "SUBTABLE").map((target) => target.subtableCode)); if (stmt.replaceSubtables.some((table) => !declared.has(table))) throw new Error("ArgumentError: REPLACE SUBTABLES contains a table not declared in INTO."); for (const target of stmt.targets.filter((target2) => target2.kind === "SUBTABLE")) { if (!target.rowIdSourceHeader || !stmt.replaceSubtables.includes(target.subtableCode)) throw new Error(`ArgumentError: CSV subtable ${target.subtableCode} requires ROW ID SOURCE and REPLACE SUBTABLES declaration.`); } } if (stmt.validationErrorTable && !tempTables) throw new Error("ArgumentError: VALIDATE ONLY INTO requires a batch."); const targets = stmt.targets; const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext); const targetCodes = targets.flatMap((target) => target.kind === "FIELD" ? [target.field] : target.children); const numberPrecision = fieldInfos.some((info) => targetCodes.includes(info.code) && info.fieldType === "NUMBER") ? await getNumberPrecisionCached(stmt.appId, client, cacheContext) : void 0; const payload = await loadImportSource(handle, /* @__PURE__ */ new Map()); const materialized = stmt.source.kind === "JSON" ? materializeJsonImportRecords(stmt.source, payload, targets, options.maxRecords ?? 1e4) : materializeCliKintoneCsvImportRecords(stmt.source, payload, targets, stmt.replaceSubtables ?? [], options.maxRecords ?? 1e4, stmt.recordNumberSourceHeader); const operation = stmt.source.kind === "CSV" ? "UPDATE" : stmt.keyFields ? "UPSERT" : "INSERT"; const prepared = prepareImportRecords(materialized, targets, fieldInfos, numberPrecision, operation); if (stmt.source.kind === "CSV") return executeCsvSubtableReplacement(stmt, materialized, prepared, fieldInfos, client, options, tempTables); assertImportRejectLimit(prepared, stmt.rejectLimit); const payloadFields = [...new Set(targets.flatMap((target) => target.kind === "FIELD" ? [target.field] : target.children))]; const errors = materializeImportValidationErrors(prepared.errors, payloadFields); const columns = [...payloadFields, ...IMPORT_VALIDATION_META_COLUMNS]; const invalidRows = prepared.invalidParentRows.size; const detail = { preflight: "ACTUAL_DATA", parents: { total: prepared.parents.length, valid: prepared.parents.length - invalidRows, invalid: invalidRows, mutationCandidates: prepared.parents.filter((parent) => parent.valid).length }, tables: Object.fromEntries(prepared.tableCounts), writesKintone: false }; const result2 = { type: "VALIDATION", operation, validatedRows: prepared.parents.length, validRows: prepared.parents.length - invalidRows, invalidRows, errorCount: errors.length, columns, errors, importDetail: detail, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : {} }; if (stmt.validationErrorTable && tempTables) appendValidationErrors( tempTables, stmt.validationErrorTable, columns, errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, /* @__PURE__ */ new Map() ); if (stmt.validateOnly) return result2; assertJsonImportHasNoRowIds(materialized); if (prepared.errors.length > 0 && !stmt.onErrorSkip) { const first = prepared.errors[0]; throw new Error(`DmlValidationError: ${first.code} ${first.message} (row=${first.parentRow}, field=${first.field})`); } if (stmt.onErrorSkip) { if (!tempTables || !stmt.errorTable) throw new Error("ArgumentError: ON ERROR SKIP requires a batch and INTO error table."); appendValidationErrors( tempTables, stmt.errorTable, columns, errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, /* @__PURE__ */ new Map() ); } const validParents = prepared.parents.filter((parent) => parent.valid); const fieldTypes = new Map(fieldInfos.map((info) => [info.code, info.fieldType])); const targetIds = validParents.map(() => void 0); if (stmt.keyFields) { for (const key of stmt.keyFields) if (!stmt.fields.includes(key)) { throw new Error(`ON DUPLICATE \u306E\u30AD\u30FC\u300C${key}\u300D\u304C UPSERT \u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093`); } const numeric = stmt.keyFields.map((key) => fieldTypes.get(key) === "NUMBER"); const sourceKeys = /* @__PURE__ */ new Set(); const rowKeys = validParents.map((parent) => stmt.keyFields.map((key) => String(parent.top[key]?.value ?? ""))); for (const parts of rowKeys) { const normalized = upsertNormalizedKey(parts, numeric); if (sourceKeys.has(normalized)) throw new Error("ERR_KEY_DUP_SOURCE: UPSERT \u30BD\u30FC\u30B9\u5185\u3067\u30AD\u30FC\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059"); sourceKeys.add(normalized); } const targetsIndex = await resolveUpsertTargets(stmt.appId, stmt.keyFields, rowKeys, client, options, fieldTypes); rowKeys.forEach((parts, index) => { targetIds[index] = lookupUpsertTarget(targetsIndex, parts); }); } const tableCodes = targets.filter((target) => target.kind === "SUBTABLE").map((target) => target.subtableCode); const existingById = /* @__PURE__ */ new Map(); const updateIds = targetIds.filter((id) => id !== void 0); for (const chunk3 of splitChunks([...new Set(updateIds)], 100)) { const response = await client.getRecords({ app: stmt.appId, query: `$id in (${chunk3.join(",")}) limit 500`, fields: ["$id", "$revision", ...tableCodes] }); for (const record2 of response.records) { const id = Number(record2["$id"]?.value); const revision = Number(record2["$revision"]?.value); if (Number.isFinite(id)) existingById.set(id, { id, ...Number.isFinite(revision) ? { revision } : {}, record: record2 }); } } const writePlan = buildJsonSubtableWritePlan(validParents, targetIds, existingById); const importDetail = { kind: "IMPORT_JSON_SUBTABLE", rowIdPolicy: "DROP_AND_RENUMBER_ALL", parentsToWrite: writePlan.length, insertedParents: writePlan.filter((parent) => parent.mode === "INSERT").length, updatedParents: writePlan.filter((parent) => parent.mode === "UPDATE").length, hasDeletes: writePlan.some((parent) => parent.tables.some((table) => table.deleteRows > 0)), parents: writePlan.map((parent) => ({ parentRow: parent.parentRow, mode: parent.mode, ...parent.targetId === void 0 ? {} : { targetId: parent.targetId }, tables: parent.tables })) }; if (writePlan.length > 0) { if (!options.confirm) throw new Error("UnsupportedError: JSON IMPORT subtable mutation requires explicit confirmation detail approval."); const ok = await options.confirm(writePlan.length, stmt.keyFields ? "UPDATE" : "INSERT", { statementIndex: 0, statementCount: 1, statementType: "IMPORT", targetAppId: stmt.appId, importDetail }); if (!ok) throw new OperationCancelledError(stmt.keyFields ? "UPDATE" : "INSERT", writePlan.length); } const toScalarMap = (record2) => new Map( Object.entries(record2).map(([code, field]) => [code, field.value]) ); const payloadFor = (parent) => buildJsonImportRecordPayload( toScalarMap(parent.top), new Map([...parent.subtables].map(([table, rows]) => [table, rows.map((row) => ({ values: toScalarMap(row) }))])) ); const inserts = writePlan.filter((parent) => parent.mode === "INSERT"); const updates = writePlan.filter((parent) => parent.mode === "UPDATE"); const createdIds = []; for (let i = 0; i < inserts.length; i += 100) { const response = await client.postRecords({ app: stmt.appId, records: inserts.slice(i, i + 100).map(payloadFor) }); createdIds.push(response.ids); } for (let i = 0; i < updates.length; i += 100) await client.putRecords({ app: stmt.appId, records: updates.slice(i, i + 100).map((parent) => ({ id: parent.targetId, ...parent.revision === void 0 ? {} : { revision: parent.revision }, record: payloadFor(parent) })) }); return stmt.keyFields ? { type: "UPSERT", insertedCount: createdIds.flat().length, updatedCount: updates.length, affectedRows: writePlan.length, skippedRows: prepared.invalidParentRows.size, rejectLimit: stmt.rejectLimit, ...stmt.errorTable ? { errTable: stmt.errorTable } : {}, importDetail } : { type: "INSERT", createdIds, insertedCount: createdIds.flat().length, affectedRows: writePlan.length, skippedRows: prepared.invalidParentRows.size, rejectLimit: stmt.rejectLimit, ...stmt.errorTable ? { errTable: stmt.errorTable } : {}, importDetail }; } if (stmt.writeMode === "UPDATE_RECORD_NUMBER") { return executeImportRecordNumberUpdate( stmt, handle, client, options, cacheContext, tempTables ); } const common = { appId: stmt.appId, fields: stmt.fields, select: importPlaceholderSelect(), validateOnly: stmt.validateOnly, validationErrorTable: stmt.validationErrorTable, onErrorSkip: stmt.onErrorSkip, errorTable: stmt.errorTable, rejectLimit: stmt.rejectLimit, checkGroups: stmt.checkGroups }; const generated = stmt.keyFields ? { type: "UPSERT_SELECT", ...common, keyFields: stmt.keyFields } : { type: "INSERT_SELECT", ...common }; const executionSource = { source: stmt.source, handle, cache: /* @__PURE__ */ new Map() }; importSourceByDmlStatement.set(generated, executionSource); const withAudit = (result2) => { if (executionSource.audit) Object.assign(result2, { importAudit: executionSource.audit }); return result2; }; if (generated.validateOnly) { if (generated.validationErrorTable && !tempTables) throw new Error("ArgumentError: VALIDATE ONLY INTO requires a batch."); const result2 = await executeDmlValidation(generated, client, { ...options, onLimitReached: "error" }, cacheContext, tempTables, 1); if (generated.validationErrorTable && tempTables) { appendValidationErrors( tempTables, generated.validationErrorTable, result2.columns, result2.errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, materializedMetaByValidationResult.get(result2) ?? /* @__PURE__ */ new Map() ); } return withAudit(result2); } if (generated.onErrorSkip) { if (!tempTables) throw new Error("ArgumentError: ON ERROR SKIP requires a batch."); const result2 = await (generated.type === "UPSERT_SELECT" ? executeOnErrorSkip(generated, client, options, cacheContext, tempTables, 1) : executeOnErrorSkip(generated, client, options, cacheContext, tempTables, 1)); return withAudit(result2); } const result = await (generated.type === "UPSERT_SELECT" ? executeUpsertSelect(generated, client, options, cacheContext, tempTables) : executeInsertSelect(generated, client, options, cacheContext, tempTables)); return withAudit(result); } async function executeCsvSubtableReplacement(stmt, materialized, preparedBase, fieldInfos, client, options, tempTables) { if (!stmt.recordNumberSourceHeader || !stmt.replaceSubtables?.length) throw new Error("InternalError: incomplete CSV subtable replacement AST."); assertNoDuplicateCsvSubtableRowIds(materialized.records); const rawKeys = materialized.records.map((record2) => record2.recordNumberSourceValue ?? ""); const keyPlan = preflightImportRecordNumbers(rawKeys, stmt.recordNumberSourceHeader); const tableCodes = [...stmt.replaceSubtables]; const ownershipTableCodes = [...new Set(fieldInfos.filter((info) => !info.inSubtable && info.fieldType === "SUBTABLE").map((info) => info.code))]; const allRecords = await fetchAll(client.getRecords, stmt.appId, "", ["$id", "$revision", ...ownershipTableCodes], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" }); const existingById = /* @__PURE__ */ new Map(); const ownership = /* @__PURE__ */ new Map(); for (const record2 of allRecords) { const id = Number(record2["$id"]?.value); const revision = Number(record2["$revision"]?.value); if (!Number.isFinite(id)) continue; existingById.set(id, { id, ...Number.isFinite(revision) ? { revision } : {}, record: record2 }); for (const table of ownershipTableCodes) { const rows = record2[table]?.value; if (!Array.isArray(rows)) continue; for (const row of rows) if (row.id) { const owners = ownership.get(row.id) ?? []; owners.push({ parentId: id, table }); ownership.set(row.id, owners); } } } const targetIds = keyPlan.normalized.map((key) => key === null ? void 0 : Number(key)); const parents = preparedBase.parents.map((parent, index) => { const errors2 = [...parent.errors]; for (const error51 of keyPlan.errors[index]) errors2.push({ operation: "UPDATE", parentRow: parent.parentRow, field: error51.field, code: error51.code, message: error51.message, sourceValues: materialized.records[index].top }); const targetId = targetIds[index]; if (targetId !== void 0 && !existingById.has(targetId)) errors2.push({ operation: "UPDATE", parentRow: parent.parentRow, field: stmt.recordNumberSourceHeader, code: "ERR_RECORD_NUMBER_NOT_FOUND", message: `record number ${targetId} does not exist in APP${stmt.appId}`, sourceValues: materialized.records[index].top }); return { ...parent, valid: errors2.length === 0, errors: errors2 }; }); const initialPlan = buildCsvSubtableReplacementPlan(materialized.records, parents, targetIds, existingById, ownership); const planErrors = initialPlan.flatMap((parent) => [...parent.errors]); const invalidParentRows = new Set(initialPlan.filter((parent) => !parent.valid).map((parent) => parent.parentRow)); const prepared = { ...preparedBase, parents, errors: planErrors, invalidParentRows }; assertImportRejectLimit(prepared, stmt.rejectLimit); const validPlan = initialPlan.filter((parent) => parent.valid); const allTables = initialPlan.flatMap((parent) => parent.tables); const sum = (table, key) => allTables.filter((item) => item.table === table).reduce((n, item) => n + Number(item[key]), 0); const tableDetail = Object.fromEntries(tableCodes.map((table) => [table, { existingRows: sum(table, "existingRows"), inputRows: sum(table, "inputRows"), updateRows: sum(table, "updateRows"), addRows: sum(table, "addRows"), deleteRows: sum(table, "deleteRows"), rowIdNotFound: sum(table, "rowIdNotFound") }])); const importDetail = { kind: "IMPORT_CSV_SUBTABLE_REPLACE", rowIdPolicy: "PRESERVE_EXISTING", parentsToWrite: validPlan.length, insertedParents: 0, updatedParents: validPlan.length, hasDeletes: validPlan.some((parent) => parent.tables.some((table) => table.deleteRows > 0)), totalDeleteRows: validPlan.flatMap((parent) => parent.tables).reduce((n, table) => n + table.deleteRows, 0), rowIdNotFound: validPlan.flatMap((parent) => parent.tables).reduce((n, table) => n + table.rowIdNotFound, 0), invalidParents: invalidParentRows.size, parents: validPlan.map((parent) => ({ parentRow: parent.parentRow, mode: "UPDATE", targetId: parent.targetId, tables: parent.tables })) }; const payloadFields = [...new Set(stmt.targets.flatMap((target) => target.kind === "FIELD" ? [target.field] : target.children))]; const errors = materializeImportValidationErrors(planErrors, payloadFields); const columns = [...payloadFields, ...IMPORT_VALIDATION_META_COLUMNS]; if (stmt.validateOnly) { if (stmt.validationErrorTable && !tempTables) throw new Error("ArgumentError: VALIDATE ONLY INTO requires a batch."); if (stmt.validationErrorTable && tempTables) appendValidationErrors(tempTables, stmt.validationErrorTable, columns, errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, /* @__PURE__ */ new Map()); return { type: "VALIDATION", operation: "UPDATE", validatedRows: parents.length, validRows: parents.length - invalidParentRows.size, invalidRows: invalidParentRows.size, errorCount: errors.length, columns, errors, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : {}, importDetail: { preflight: "ACTUAL_DATA", parents: { total: parents.length, valid: validPlan.length, invalid: invalidParentRows.size, mutationCandidates: validPlan.length }, tables: tableDetail, rowIdPolicy: "PRESERVE_EXISTING", rowIdNotFound: importDetail.rowIdNotFound, writesKintone: false } }; } if (planErrors.length && !stmt.onErrorSkip) { const first = planErrors[0]; throw new Error(`DmlValidationError: ${first.code} ${first.message} (row=${first.parentRow}, field=${first.field})`); } if (stmt.onErrorSkip) { if (!tempTables || !stmt.errorTable) throw new Error("ArgumentError: ON ERROR SKIP requires a batch and INTO error table."); appendValidationErrors(tempTables, stmt.errorTable, columns, errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, /* @__PURE__ */ new Map()); } if (validPlan.length) { if (!options.supportsImportConfirmDetail || !options.confirm) throw new Error("UnsupportedError: CSV subtable replacement requires explicit rendered detail approval."); const ok = await options.confirm(validPlan.length, "UPDATE", { statementIndex: 0, statementCount: 1, statementType: "IMPORT", targetAppId: stmt.appId, importDetail }); if (!ok) throw new OperationCancelledError("UPDATE", validPlan.length); } const scalarMap = (record2) => new Map(Object.entries(record2).map(([code, field]) => [code, field.value])); for (const parent of validPlan) { const record2 = buildImportRecordPayload(scalarMap(parent.top), new Map([...parent.subtables].map(([table, rows]) => [table, rows.map((row) => ({ ...row.rowId ? { rowId: row.rowId } : {}, values: scalarMap(row.record) }))])), "PRESERVE"); await client.putRecords({ app: stmt.appId, records: [{ id: parent.targetId, ...parent.revision === void 0 ? {} : { revision: parent.revision }, record: record2 }] }); } return { type: "UPDATE", updatedCount: validPlan.length, affectedRows: validPlan.length, skippedRows: invalidParentRows.size, rejectLimit: stmt.rejectLimit, ...stmt.errorTable ? { errTable: stmt.errorTable } : {}, importDetail }; } async function executeImportRecordNumberUpdate(stmt, handle, client, options, cacheContext, tempTables) { if (stmt.source.kind !== "CSV" || stmt.source.mappingMode !== "BY_NAME" || !stmt.recordNumberSourceHeader) { throw new Error("InternalError: invalid IMPORT UPDATE AST."); } if (new Set(stmt.fields).size !== stmt.fields.length) throw new Error("ArgumentError: DML target fields contain duplicates."); const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext); const payload = await loadImportSource(handle, /* @__PURE__ */ new Map()); const sourceTable = materializeCsvDmlSource( stmt.source, payload, options.maxRecords ?? 1e4, stmt.fields, fieldInfos, stmt.recordNumberSourceHeader ); const keyValues = sourceTable.recordNumberSourceValues; if (!keyValues) throw new Error("InternalError: record-number source values were not materialized."); const keyPlan = preflightImportRecordNumbers(keyValues, stmt.recordNumberSourceHeader); const matchedIds = /* @__PURE__ */ new Set(); const lookupKeys = [...new Set(keyPlan.normalized.filter((key) => key !== null))]; for (let i = 0; i < lookupKeys.length; i += 100) { const chunk3 = lookupKeys.slice(i, i + 100); const response = await client.getRecords({ app: stmt.appId, query: `$id in (${chunk3.join(",")}) limit 500`, fields: ["$id"] }); for (const record2 of response.records) { const id = record2["$id"]?.value; if (typeof id === "string" && id !== "") matchedIds.add(id.replace(/^0+(?=\d)/, "")); } } const infoByCode = new Map(fieldInfos.map((info) => [info.code, info])); const evaluationTypes = new Map(stmt.fields.map((field) => [field, infoByCode.get(field)?.fieldType ?? "SINGLE_LINE_TEXT"])); const candidates = sourceTable.rows.map((row, index) => { const key = keyPlan.normalized[index]; const preErrors = [ ...sourceTable.importRowErrors?.[index] ?? [], ...keyPlan.errors[index] ]; if (key !== null && !matchedIds.has(key)) preErrors.push({ field: stmt.recordNumberSourceHeader, code: "ERR_RECORD_NUMBER_NOT_FOUND", message: `record number ${key} does not exist in APP${stmt.appId}` }); return { rowNumber: index + 1, operation: "UPDATE", mode: "update", ...key !== null && matchedIds.has(key) ? { targetId: Number(key) } : {}, payload: new Map([ [stmt.recordNumberSourceHeader, keyValues[index]], ...stmt.fields.map((field) => [field, row[field] ?? ""]) ]), preErrors, record: {}, evaluationRow: row, evaluationFieldTypes: evaluationTypes }; }); const diagnosticFields = [stmt.recordNumberSourceHeader, ...stmt.fields]; const validation = validateDmlCandidates( candidates, "UPDATE", diagnosticFields, stmt.fields, fieldInfos, 1, numberPrecision, stmt.checkGroups ?? [], false ); const columns = [...diagnosticFields, ...VALIDATION_META_COLUMNS]; const validationResult = { type: "VALIDATION", operation: "UPDATE", validatedRows: candidates.length, validRows: candidates.length - validation.invalidRows, invalidRows: validation.invalidRows, errorCount: validation.errors.length, columns, errors: validation.errors, ...stmt.validationErrorTable ?? stmt.errorTable ? { errTable: stmt.validationErrorTable ?? stmt.errorTable } : {} }; Object.assign(validationResult, { importAudit: sourceTable.importAudit }); if (stmt.validateOnly) { if (stmt.validationErrorTable && !tempTables) throw new Error("ArgumentError: VALIDATE ONLY INTO requires a batch."); if (stmt.validationErrorTable && tempTables) appendValidationErrors( tempTables, stmt.validationErrorTable, columns, validation.errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, /* @__PURE__ */ new Map() ); return validationResult; } if (!stmt.onErrorSkip && validation.invalidRows > 0) { const first = validation.errors[0]; throw new Error(`DmlValidationError: ${first.$err_code} ${first.$err_message} (row=${first.$err_row}, field=${first.$err_field})`); } if (stmt.onErrorSkip) { if (!tempTables || !stmt.errorTable) throw new Error("ArgumentError: ON ERROR SKIP requires a batch."); appendValidationErrors( tempTables, stmt.errorTable, columns, validation.errors, options.tempTableMaxRows ?? TEMP_TABLE_MAX_ROWS, /* @__PURE__ */ new Map() ); if (stmt.rejectLimit != null && validation.invalidRows > stmt.rejectLimit) { throw new RejectLimitExceededError( `rejected rows (${validation.invalidRows}) exceed REJECT LIMIT (${stmt.rejectLimit}).`, validationResult ); } } const valid = candidates.filter((candidate) => !validation.invalidRowNumbers.has(candidate.rowNumber)); if (options.confirm) { const ok = await options.confirm(valid.length, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", valid.length); } const updates = valid.map((candidate) => ({ id: candidate.targetId, record: candidate.record })); for (let i = 0; i < updates.length; i += 100) { await client.putRecords({ app: stmt.appId, records: updates.slice(i, i + 100) }); } const result = { type: "UPDATE", updatedCount: updates.length, ...stmt.onErrorSkip ? { affectedRows: updates.length, skippedRows: validation.invalidRows, rejectLimit: stmt.rejectLimit ?? null, errTable: stmt.errorTable } : {} }; Object.assign(result, { insertedCount: 0, importAudit: sourceTable.importAudit }); return result; } async function materializeDmlSource(stmt, client, options, cacheContext, tempTables, targetFields) { const imported = importSourceByDmlStatement.get(stmt); if (!imported) { const selected2 = tempTables && tempTables.size > 0 ? await executeQueryWithCte(stmt.select, client, options, tempTables, cacheContext, true) : await executeSelect(stmt.select, client, options, cacheContext, void 0, true); return { rows: selected2.rows, columns: selected2.columns, columnMeta: materializedMetaBySelectResult.get(selected2) }; } const payload = await loadImportSource(imported.handle, imported.cache); const rowLimit = options.maxRecords ?? 1e4; const targetByCode = new Map((targetFields ?? []).map((info) => [info.code, info])); const jsonTargets = stmt.fields.map((code) => ({ code, fieldType: targetByCode.get(code)?.fieldType ?? "SINGLE_LINE_TEXT" })); const raw = imported.source.kind === "JSON" ? materializeJsonDmlSource(imported.source, payload, jsonTargets, rowLimit) : materializeCsvDmlSource(imported.source, payload, rowLimit, stmt.fields, targetFields); imported.audit = raw.importAudit; if (imported.source.kind === "JSON") return raw; if (!imported.source.projection) return raw; const projection = bindImportProjection(imported.source.projection); const tables = new Map(tempTables ?? []); tables.set(IMPORT_PROJECTION_SOURCE, raw); const selected = await executeQueryWithCte(projection, client, { ...options, onLimitReached: "error" }, tables, cacheContext, true); return { rows: selected.rows, columns: selected.columns, columnMeta: materializedMetaBySelectResult.get(selected) }; } var dmlSourceMaterializer = { materialize: materializeDmlSource }; function assertNoImportRowErrors(table) { for (let rowIndex = 0; rowIndex < (table.importRowErrors?.length ?? 0); rowIndex++) { const first = table.importRowErrors?.[rowIndex]?.[0]; if (first) { throw new Error(`DmlValidationError: ${first.code} ${first.message} (row=${rowIndex + 1}, field=${first.field})`); } } } async function executeInsertSelect(stmt, client, options, cacheContext, cteCache) { if (stmt.checkGroups?.length) return executeCheckedPlainDml(stmt, client, options, cacheContext, cteCache); const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext); const sourceTable = await dmlSourceMaterializer.materialize(stmt, client, options, cacheContext, cteCache, fieldInfos); const { rows, columns } = sourceTable; assertNoImportRowErrors(sourceTable); if (columns.length !== stmt.fields.length) { const emptySourceHint = columns.length === 0 && rows.length === 0 ? "\u3002\u7D50\u679C\u304C 0 \u884C\u306E\u305F\u3081\u5217\u3092\u7279\u5B9A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08SELECT * \u3092\u7A7A\u30BD\u30FC\u30B9\u306B\u4F7F\u3046\u3068\u5217\u3092\u6C7A\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002\u660E\u793A\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF09" : ""; throw new Error( `SELECT \u306E\u5217\u6570\uFF08${columns.length}\uFF09\u3068 INSERT \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u6570\uFF08${stmt.fields.length}\uFF09\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093${emptySourceHint}` ); } if (options.confirm) { const ok = await options.confirm(rows.length, "INSERT"); if (!ok) throw new OperationCancelledError("INSERT", rows.length); } const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const allRecords = rows.map((row, rowIndex) => { const record2 = {}; stmt.fields.forEach((field, i) => { if (sourceTable.importPresence && !sourceTable.importPresence[rowIndex]?.has(field)) return; const raw = row[columns[i]] ?? ""; record2[field] = { value: convertProcessRowValue(raw, fieldTypes.get(field)) }; }); return record2; }); allRecords.forEach((record2) => assertValidDmlRecords([record2], stmt.fields.filter((field) => field in record2), fieldInfos, numberPrecision)); const createdIds = []; for (let i = 0; i < allRecords.length; i += 100) { const batch = allRecords.slice(i, i + 100); const res = await client.postRecords({ app: stmt.appId, records: batch }); createdIds.push(res.ids); } return { type: "INSERT", createdIds, insertedCount: createdIds.flat().length }; } async function executeUpdate(stmt, client, options, cacheContext, tempTables) { if (stmt.applyBlocks?.length) { return executeApplyPatchUpdate(stmt, client, options, cacheContext); } if (stmt.checkGroups?.length && isConstantFalseWhere(stmt.where)) { const fieldInfos2 = await loadWritableTopLevelDmlFields( stmt.appId, stmt.assignments.map((assignment) => assignment.field), client, cacheContext ); await loadNumberPrecisionForTargets( stmt.appId, stmt.assignments.map((assignment) => assignment.field), fieldInfos2, client, cacheContext ); const fieldTypes2 = await getFieldTypeMap(stmt.appId, client, cacheContext); assertUpdateCheckRefs(stmt, fieldTypes2); assertCheckComparisonTypes(stmt, updateEvaluationTypes(fieldTypes2, stmt.appId)); await assertDmlWhereCapability(stmt, client, cacheContext); return { type: "UPDATE", updatedCount: 0 }; } if (stmt.checkGroups?.length) return executeCheckedPlainDml(stmt, client, options, cacheContext, tempTables); if (stmt.subtableCode) { await assertDmlWhereCapability(stmt, client, cacheContext); return executeUpdateSubtable(stmt, client, options, cacheContext); } const fieldInfos = await loadWritableTopLevelDmlFields( stmt.appId, stmt.assignments.map((assignment) => assignment.field), client, cacheContext ); const targetFields = stmt.assignments.map((assignment) => assignment.field); const numberPrecision = await loadNumberPrecisionForTargets( stmt.appId, targetFields, fieldInfos, client, cacheContext ); await assertDmlWhereCapability(stmt, client, cacheContext); if (isConstantFalseWhere(stmt.where)) return { type: "UPDATE", updatedCount: 0 }; if (stmt.from != null) { return executeUpdateFrom(stmt, stmt.from, client, options, cacheContext, tempTables); } const maxRecords2 = options.maxRecords ?? 1e4; await resolveSetSubqueries(stmt.assignments, client, options, cacheContext); const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); if (hasRowDependentAssignment(stmt)) { const getParams2 = updateToGetQueryForArith(stmt); const resolved2 = await fetchRecordsForSharedPlan( client.getRecords, getParams2.app, getParams2.query, [...getParams2.fields], { maxRecords: maxRecords2, parallel: options.fetchParallel ?? 1 } ); const records = resolved2.records; const batches2 = updateToPutBatchesArith(stmt, records, fieldTypes); assertValidDmlRecords(batches2.flatMap((batch) => batch.records.map((entry) => entry.record)), targetFields, fieldInfos, numberPrecision); if (options.confirm) { const ok = await options.confirm(records.length, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", records.length); } for (const batch of batches2) { await client.putRecords(batch); } return { type: "UPDATE", updatedCount: records.length }; } const getParams = updateToGetQuery(stmt); const resolved = await resolveDmlTargetIds( client.getRecords, getParams.app, getParams.query, { maxRecords: maxRecords2, parallel: options.fetchParallel ?? 1 } ); const ids = resolved.ids; const batches = updateToPutBatches(stmt, ids, fieldTypes); assertValidDmlRecords(batches.flatMap((batch) => batch.records.map((entry) => entry.record)), targetFields, fieldInfos, numberPrecision); if (options.confirm) { const ok = await options.confirm(ids.length, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", ids.length); } for (const batch of batches) { await client.putRecords(batch); } return { type: "UPDATE", updatedCount: ids.length }; } async function executeApplyPatchUpdate(stmt, client, options, cacheContext, statementNumber = 1) { if (!stmt.validateOnly && options.allowApplyMutation !== true) { throw new Error("UnsupportedError: APPLY mutation requires allowApplyMutation=true"); } if (!isSinglePositiveRecordIdWhere(stmt.where)) { return executeMultipleParentApplyPreflight(stmt, client, options, cacheContext, statementNumber); } const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext); const metadata = resolveApplyPatchMetadata(stmt, fieldInfos); const fields = collectApplySnapshotFields(stmt, fieldInfos); const requestedId = getApplyParentId(stmt); const response = await client.getRecords({ app: stmt.appId, query: `$id = ${requestedId} limit 2`, fields: [...fields] }); if (response.records.length === 0) { throw new Error(`ArgumentError: APPLY parent $id ${requestedId} does not exist.`); } if (response.records.length !== 1) { throw new Error(`ArgumentError: APPLY parent $id ${requestedId} returned multiple records.`); } const actualId = Number(response.records[0]["$id"]?.value); if (actualId !== requestedId) { throw new Error(`ArgumentError: APPLY snapshot $id ${actualId} does not match requested $id ${requestedId}.`); } requireRevision(response.records[0]); const plan = buildApplyPatchPlan({ statement: stmt, snapshot: response.records[0], fieldInfos, metadata }); const fieldIndex = buildPostImageFieldIndex( fieldInfos, stmt.assignments.map((assignment) => assignment.field) ); const numberPrecision = postImageNeedsNumberPrecision(plan.postImage, fieldIndex) ? await getNumberPrecisionCached(stmt.appId, client, cacheContext) : void 0; const validation = validatePostImage(plan.postImage, fieldIndex, numberPrecision, statementNumber); if (!stmt.validateOnly && validation.errorCount > 0) { throw new Error(`ArgumentError: APPLY post-image validation failed: ${JSON.stringify({ columns: validation.columns, errors: validation.errors })}`); } const dmlMaxRows = resolveApplyGuardLimit(options.dmlMaxRows, "dmlMaxRows", DEFAULT_APPLY_MAX_ROWS); const dmlMaxSubtableRows = resolveApplyGuardLimit(options.dmlMaxSubtableRows, "dmlMaxSubtableRows", DEFAULT_APPLY_MAX_SUBTABLE_ROWS); const wouldExceed = plan.parentRows > dmlMaxRows || plan.changedSubtableRows > dmlMaxSubtableRows; if (stmt.validateOnly) { const diagnostic3 = buildPreparedApplyUpdateDiagnostic({ plans: [plan], records: applyPatchPlanToKintone(plan).records, validations: [], guards: { revisionRequired: true, parentRows: plan.parentRows, dmlMaxRows, subtableRows: plan.changedSubtableRows, dmlMaxSubtableRows, wouldExceed } }); const result = { type: "VALIDATION", operation: "UPDATE", validatedRows: 1, validRows: validation.invalidRows === 0 ? 1 : 0, invalidRows: validation.invalidRows === 0 ? 0 : 1, errorCount: validation.errorCount, columns: [...validation.columns], errors: validation.errors, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : {}, apply: applyValidationDetailsFromBranch(diagnostic3.branches[0]), guards: applyGuardFromDiagnosticBranch(diagnostic3.branches[0]), deletedRows: { total: plan.tables.reduce((sum, table) => sum + table.deletedRows, 0), parentRows: plan.tables.some((table) => table.deletedRows > 0) ? 1 : 0 }, diagnostic: diagnostic3 }; materializedMetaByValidationResult.set( result, applyValidationColumnMeta(validation.columns, fieldInfos, stmt.appId) ); return result; } if (plan.parentRows > dmlMaxRows) { throw new Error(`ArgumentError: APPLY parent rows (${plan.parentRows}) exceed dmlMaxRows (${dmlMaxRows}).`); } if (plan.changedSubtableRows > dmlMaxSubtableRows) { throw new Error( `ArgumentError: APPLY changed subtable rows (${plan.changedSubtableRows}) exceed dmlMaxSubtableRows (${dmlMaxSubtableRows}).` ); } const normalizedPlan = normalizeApplyPatchPlan(plan, validation.normalizedRecord); const putParams = applyPatchPlanToKintone(normalizedPlan); const diagnostic2 = buildPreparedApplyUpdateDiagnostic({ plans: [normalizedPlan], records: putParams.records, validations: [], guards: { revisionRequired: true, parentRows: plan.parentRows, dmlMaxRows, subtableRows: plan.changedSubtableRows, dmlMaxSubtableRows, wouldExceed } }); if (options.confirm) { const applyDetail = buildApplyConfirmDetailFromDiagnostic(diagnostic2, false); const ok = await options.confirm(plan.parentRows, "UPDATE", { statementIndex: 0, statementCount: 1, statementType: "UPDATE", targetAppId: stmt.appId, applyDetail, applyDiagnostic: diagnostic2 }); if (!ok) throw new OperationCancelledError("UPDATE", plan.parentRows); } await client.putRecords(putParams); return { type: "UPDATE", updatedCount: plan.parentRows, diagnostic: withApplyDiagnosticProgress(diagnostic2, { successfulChunks: 1, successfulParents: plan.parentRows }) }; } async function executeMultipleParentApplyPreflight(stmt, client, options, cacheContext, statementNumber) { const dmlMaxRows = resolveApplyGuardLimit(options.dmlMaxRows, "dmlMaxRows", DEFAULT_APPLY_MAX_ROWS); const dmlMaxSubtableRows = resolveApplyGuardLimit( options.dmlMaxSubtableRows, "dmlMaxSubtableRows", DEFAULT_APPLY_MAX_SUBTABLE_ROWS ); const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext); const metadata = resolveApplyPatchMetadata(stmt, fieldInfos); let snapshots; if (usesApplyParentResidualSelection(stmt)) { snapshots = await selectApplyParentSnapshots(stmt, client, options, fieldInfos, cacheContext); } else { const fields = collectApplySnapshotFields(stmt, fieldInfos); const baseQuery = updateToGetQuery(stmt).query; const detectionLimit = dmlMaxRows + 1; snapshots = await fetchAll(client.getRecords, stmt.appId, baseQuery, [...fields], { pageSize: Math.min(500, detectionLimit), parallel: options.fetchParallel ?? 1, maxRecords: detectionLimit, stopAfter: detectionLimit, onLimit: "error" }); } if (!stmt.validateOnly && snapshots.length > dmlMaxRows) { throw new Error(`ArgumentError: APPLY parent rows (${snapshots.length}) exceed dmlMaxRows (${dmlMaxRows}).`); } const prepared = await prepareApplyPatchWrite({ statement: stmt, snapshots, fieldInfos, metadata, dmlMaxRows, dmlMaxSubtableRows, statementNumber, loadNumberPrecision: () => getNumberPrecisionCached(stmt.appId, client, cacheContext) }); if (stmt.validateOnly) return materializePreparedApplyValidation(stmt, prepared, fieldInfos); assertApplyPublicWriteScope("phase15b", stmt); const diagnostic2 = buildPreparedApplyUpdateDiagnostic(prepared); if (options.confirm) { const applyDetail = buildApplyConfirmDetailFromDiagnostic(diagnostic2); const ok = await options.confirm(prepared.guards.parentRows, "UPDATE", { statementIndex: 0, statementCount: 1, statementType: "UPDATE", targetAppId: stmt.appId, applyDetail, applyDiagnostic: diagnostic2 }); if (!ok) throw new OperationCancelledError("UPDATE", prepared.guards.parentRows); } const result = await executePreparedApplyWrite(prepared, client, diagnostic2); return { ...result, diagnostic: withApplyDiagnosticProgress(diagnostic2, result) }; } function usesApplyParentResidualSelection(stmt) { return (stmt.applyBlocks?.length ?? 0) > 0 && !isSinglePositiveRecordIdWhere(stmt.where) && (whereHasLike(stmt.where) || whereHasKlike(stmt.where)); } function isApplyParentKlikeStatement(stmt) { const target = stmt.type === "EXPLAIN" ? stmt.query : stmt; return target.type === "UPDATE" && usesApplyParentResidualSelection(target) && whereHasKlike(target.where); } var APPLY_PARENT_UNAPPLIED_KLIKE_ERROR = "APPLY \u8907\u6570\u89AA UPDATE \u306E\u89AA WHERE \u306B\u3001\u5B89\u5168\u306B\u62BC\u3057\u4E0B\u3052\u3089\u308C\u306A\u3044 KLIKE / NOT KLIKE \u304C\u3042\u308A\u307E\u3059\u3002\nOR / NOT \u914D\u4E0B\u306A\u3069 native query \u3078\u5B8C\u5168\u306B\u9069\u7528\u3067\u304D\u306A\u3044 KLIKE \u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\nWHERE \u3092 AND \u306E\u5B89\u5168\u306A KLIKE \u6761\u4EF6\u3078\u66F8\u304D\u63DB\u3048\u308B\u304B\u3001SELECT \u3067\u78BA\u8A8D\u3057\u305F $id IN (...) \u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002"; function assertApplyParentKlikesFullyApplied(plan) { if (plan.unappliedKlikes.length > 0) throw new Error(`UnsupportedError: ${APPLY_PARENT_UNAPPLIED_KLIKE_ERROR}`); } async function selectApplyParentSnapshots(stmt, client, options, fieldInfos, cacheContext) { const topLevelInfos = fieldInfos.filter((field) => !field.inSubtable); const infoByCode = new Map(topLevelInfos.map((field) => [field.code, field])); const fieldTypes = new Map(topLevelInfos.map((field) => [field.code, field.fieldType])); const fieldOptions = new Map(topLevelInfos.flatMap((field) => field.optionOrder ? [[field.code, new Set(Object.keys(field.optionOrder))]] : [])); const selectionPlan = buildApplyParentSelectionPlan(stmt.where, { fieldTypes, fieldOptions }); assertApplyParentKlikesFullyApplied(selectionPlan); const prefilterQuery = selectionPlan.prefilter === null ? "" : whereToKintone(selectionPlan.prefilter); const fields = new Set(collectApplySnapshotFields(stmt, fieldInfos)); for (const field of collectApplyParentWhereFields(stmt.where)) fields.add(field); const resolvers = await buildApplyParentFieldResolvers( stmt.appId, stmt.where, infoByCode, client, cacheContext ); const candidates = await fetchAll( client.getRecords, stmt.appId, prefilterQuery, [...fields], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1, onLimit: "error" // prefilter は target の超集合なので stopAfter を設定せず最後まで取得する。 } ); return candidates.map((snapshot) => ({ snapshot, row: flatten(snapshot, null) })).filter(({ row }) => evalWhere( stmt.where, row, resolvers.fieldTypeResolver, selectionPlan.appliedKlikes, resolvers.fieldSemanticsResolver )).map(({ snapshot }) => snapshot); } function collectApplyParentWhereFields(where) { return collectValidateWhereFields(where); } async function buildApplyParentFieldResolvers(appId, where, infoByCode, client, cacheContext) { const orderedFields = collectOrderedWhereFields(where); const needsStatusOrder = [...orderedFields].some((field) => infoByCode.get(field)?.fieldType === "STATUS"); const statusOrder = needsStatusOrder ? await loadProcessStatusOrder(appId, client, cacheContext) : void 0; const fieldTypeResolver = (field) => field.field === "$id" ? "NUMBER" : infoByCode.get(field.field)?.fieldType; const fieldSemanticsResolver = (field) => { if (field.field === "$id") { return withFieldSemanticSource(resolveFieldSemantics({ fieldType: "__ID__" }), appId, "$id"); } const info = infoByCode.get(field.field); if (!info) return void 0; const base = info.semantics ?? resolveFieldSemantics(info); const semantics = info.fieldType === "STATUS" && statusOrder ? { ...base, optionOrder: statusOrder } : base; return withFieldSemanticSource(semantics, appId, info.code); }; return { fieldTypeResolver, fieldSemanticsResolver }; } function collectOrderedWhereFields(where) { const fields = /* @__PURE__ */ new Set(); const visit = (node) => { if (Array.isArray(node)) { node.forEach(visit); return; } if (node === null || typeof node !== "object") return; const value = node; if (value["type"] === "SELECT") return; if (value["type"] === "BINARY" && [">", "<", ">=", "<="].includes(String(value["op"]))) { const left = value["left"]; if (left?.["type"] === "FIELD" && typeof left["field"] === "string") { fields.add(left["field"]); } } Object.values(value).forEach(visit); }; visit(where); return fields; } function materializePreparedApplyInsertValidation(stmt, prepared, fieldInfos) { const errors = prepared.validations.flatMap((validation) => validation.errors); const invalidRows = prepared.validations.reduce( (sum, validation) => sum + (validation.invalidRows > 0 ? 1 : 0), 0 ); const columns = prepared.validations[0]?.columns ? [...prepared.validations[0].columns] : [ ...buildPostImageFieldIndex(fieldInfos, stmt.fields).payloadFields, ...POST_IMAGE_VALIDATION_SUFFIX_COLUMNS ]; const parentRows = prepared.guards.parentRows; const diagnostic2 = buildPreparedApplyInsertDiagnostic(prepared); const branch = diagnostic2.branches[0]; const result = { type: "VALIDATION", operation: "INSERT", validatedRows: parentRows, validRows: parentRows - invalidRows, invalidRows, errorCount: errors.length, columns, errors, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : {}, apply: applyValidationDetailsFromBranch(branch), guards: applyGuardFromDiagnosticBranch(branch), deletedRows: { total: 0, parentRows: 0 }, diagnostic: diagnostic2 }; materializedMetaByValidationResult.set(result, applyValidationColumnMeta(columns, fieldInfos, stmt.appId)); return result; } function materializePreparedApplyValidation(stmt, prepared, fieldInfos) { const validations = prepared.validations; const errors = validations.flatMap((validation) => validation.errors); const invalidRows = validations.reduce((sum, validation) => sum + (validation.invalidRows > 0 ? 1 : 0), 0); const columns = validations[0]?.columns ? [...validations[0].columns] : [ ...buildPostImageFieldIndex(fieldInfos, stmt.assignments.map((assignment) => assignment.field)).payloadFields, ...POST_IMAGE_VALIDATION_SUFFIX_COLUMNS ]; const diagnostic2 = buildPreparedApplyUpdateDiagnostic(prepared); const result = { type: "VALIDATION", operation: "UPDATE", validatedRows: prepared.guards.parentRows, validRows: prepared.guards.parentRows - invalidRows, invalidRows, errorCount: errors.length, columns, errors, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : {}, apply: applyValidationDetailsFromBranch(diagnostic2.branches[0]), guards: applyGuardFromDiagnosticBranch(diagnostic2.branches[0]), deletedRows: { total: prepared.plans.reduce( (sum, plan) => sum + plan.tables.reduce((tableSum, table) => tableSum + table.deletedRows, 0), 0 ), parentRows: prepared.plans.filter((plan) => plan.tables.some((table) => table.deletedRows > 0)).length }, diagnostic: diagnostic2 }; materializedMetaByValidationResult.set(result, applyValidationColumnMeta(columns, fieldInfos, stmt.appId)); return result; } function materializePreparedApplyUpsertValidation(stmt, prepared, fieldInfos) { const createErrors = prepared.create.validations.flatMap((validation) => validation.errors); const updateErrors = prepared.update.validations.flatMap((validation) => validation.errors); const errors = [...createErrors, ...updateErrors].map((error51) => ({ ...error51, $err_operation: "UPSERT" })); const invalidRows = new Set(errors.map((error51) => error51.$err_row)).size; const columns = prepared.create.validations[0]?.columns ?? prepared.update.validations[0]?.columns ?? [ ...buildPostImageFieldIndex(fieldInfos, stmt.fields).payloadFields, ...POST_IMAGE_VALIDATION_SUFFIX_COLUMNS ]; const diagnostic2 = buildPreparedApplyUpsertDiagnostic(prepared); const insertBranch = diagnostic2.branches.find((branch) => branch.branch === "insert"); const updateBranch = diagnostic2.branches.find((branch) => branch.branch === "update"); const createApply = applyValidationDetailsFromBranch(insertBranch); const updateApply = applyValidationDetailsFromBranch(updateBranch); const result = { type: "VALIDATION", operation: "UPSERT", validatedRows: prepared.guards.parentRows, validRows: prepared.guards.parentRows - invalidRows, invalidRows, errorCount: errors.length, columns: [...columns], errors, ...stmt.validationErrorTable ? { errTable: stmt.validationErrorTable } : {}, apply: [...createApply, ...updateApply], guards: { revisionRequired: prepared.guards.revisionRequired, parentRows: prepared.guards.parentRows, dmlMaxRows: prepared.guards.dmlMaxRows, subtableRows: prepared.guards.subtableRows, dmlMaxSubtableRows: prepared.guards.dmlMaxSubtableRows, wouldExceed: prepared.guards.wouldExceed }, applyBranches: { create: { apply: createApply, guards: applyGuardFromDiagnosticBranch(insertBranch) }, update: { apply: updateApply, guards: applyGuardFromDiagnosticBranch(updateBranch) } }, deletedRows: { total: prepared.update.plans.reduce( (sum, plan) => sum + plan.tables.reduce((tableSum, table) => tableSum + table.deletedRows, 0), 0 ), parentRows: prepared.update.plans.filter((plan) => plan.tables.some((table) => table.deletedRows > 0)).length }, diagnostic: diagnostic2 }; materializedMetaByValidationResult.set(result, applyValidationColumnMeta([...columns], fieldInfos, stmt.appId)); return result; } function applyValidationDetailsFromBranch(branch) { return branch.targets.map((target) => { const operations = target.operations.map((operation) => ({ kind: operation.kind, ...operation.matchedRows !== void 0 ? { matchedRows: operation.matchedRows ?? void 0 } : {}, ...operation.changedRows !== void 0 ? { changedRows: operation.changedRows ?? void 0 } : {}, ...operation.addedRows !== void 0 ? { addedRows: operation.addedRows ?? void 0 } : {}, ...operation.removedRows !== void 0 ? { removedRows: operation.removedRows ?? void 0 } : {}, ...operation.value !== void 0 ? { value: operation.value } : {}, ...operation.changed !== void 0 ? { changed: operation.changed } : {} })); if (target.targetKind === "SUBTABLE") { return { field: target.field, operations, changedSubtableRows: target.changedCount ?? 0, deletedRows: operationCount(target, "REMOVE") }; } return { field: target.field, operations, changedSubtableRows: 0, deletedRows: 0, multiValue: { fieldType: target.fieldType ?? "UNKNOWN", addedValues: operationCount(target, "ADD"), removedValues: operationCount(target, "REMOVE_VALUE"), changedValues: target.changedCount ?? 0, postImages: target.postImages ?? [] } }; }); } function applyGuardFromDiagnosticBranch(branch) { if (branch.guards.parentRows === null || branch.guards.subtableRows === null || branch.guards.wouldExceed === null) { throw new Error("InternalError: runtime APPLY diagnostic guard contains unknown counts."); } return { revisionRequired: branch.guards.revisionRequired, parentRows: branch.guards.parentRows, dmlMaxRows: branch.guards.dmlMaxRows, subtableRows: branch.guards.subtableRows, dmlMaxSubtableRows: branch.guards.dmlMaxSubtableRows, wouldExceed: branch.guards.wouldExceed }; } var DEFAULT_APPLY_MAX_ROWS = 100; var DEFAULT_APPLY_MAX_SUBTABLE_ROWS = 500; function resolveApplyGuardLimit(value, name, fallback) { const resolved = value ?? fallback; if (!Number.isSafeInteger(resolved) || resolved <= 0) { throw new Error(`ArgumentError: ${name} must be a positive safe integer.`); } return resolved; } function applyValidationColumnMeta(columns, fieldInfos, appId) { const fields = new Map(fieldInfos.filter((field) => !field.inSubtable).map((field) => [field.code, field])); const numericMeta = /* @__PURE__ */ new Set(["$id", "$err_statement", "$err_row"]); const meta3 = /* @__PURE__ */ new Map(); for (const column of columns) { if (column === "$id") { meta3.set(column, { sortKind: "number", fieldType: "RECORD_NUMBER", semantics: resolveFieldSemantics({ fieldType: "RECORD_NUMBER" }) }); continue; } const field = fields.get(column); if (field) { meta3.set(column, materializedMetaFromFieldInfo(field, appId)); continue; } meta3.set(column, syntheticColumnMeta(numericMeta.has(column) ? "number" : "string")); } return meta3; } async function executeUpdateFrom(stmt, from, client, options, cacheContext, tempTables) { const matched = await resolveUpdateFromMatchedRecords(stmt, from, client, options, cacheContext, tempTables); const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const batches = updateFromToPutBatches(stmt, matched, fieldTypes); const targetFields = stmt.assignments.map((assignment) => assignment.field); const fieldInfos = await getFieldsCached(stmt.appId, client, cacheContext); const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, targetFields, fieldInfos, client, cacheContext); assertValidDmlRecords(batches.flatMap((batch) => batch.records.map((entry) => entry.record)), targetFields, fieldInfos, numberPrecision); if (options.confirm) { const ok = await options.confirm(matched.length, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", matched.length); } for (const batch of batches) await client.putRecords(batch); return { type: "UPDATE", updatedCount: matched.length }; } function collectUpdateFromTargetFields(stmt) { const fields = /* @__PURE__ */ new Set(["$id"]); if (stmt.from) fields.add(stmt.from.targetJoinField); const visit = (node) => { if (Array.isArray(node)) { node.forEach(visit); return; } if (node === null || typeof node !== "object") return; const obj = node; if (obj["type"] === "FIELD_REF" && typeof obj["field"] === "string") fields.add(obj["field"]); for (const value of Object.values(obj)) visit(value); }; for (const assignment of stmt.assignments) { if (assignment.value.type !== "SOURCE_FIELD") visit(assignment.value); } return [...fields]; } async function executeDelete(stmt, client, options, cacheContext) { await assertDmlWhereCapability(stmt, client, cacheContext); if (isConstantFalseWhere(stmt.where)) return { type: "DELETE", deletedCount: 0 }; if (stmt.subtableCode) { return executeDeleteSubtable(stmt, client, options, cacheContext); } const getParams = deleteToGetQuery(stmt); const resolved = await resolveDmlTargetIds( client.getRecords, getParams.app, getParams.query, { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 } ); const ids = resolved.ids; if (options.confirm) { const ok = await options.confirm(ids.length, "DELETE"); if (!ok) throw new OperationCancelledError("DELETE", ids.length); } const batches = deleteToDeleteBatches(stmt.appId, ids); for (const batch of batches) { await client.deleteRecords(batch); } return { type: "DELETE", deletedCount: ids.length }; } async function executeUpsert(stmt, client, options, cacheContext) { if (stmt.onInsertApplyBlocks?.length || stmt.onUpdateApplyBlocks?.length) { return executeApplyUpsert(stmt, client, options, cacheContext); } if (stmt.checkGroups?.length) return executeCheckedPlainDml(stmt, client, options, cacheContext); const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext); const toInsert = []; const toUpdate = []; const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const rowKeyValues = buildUpsertRowKeyValues(stmt); const targetIndex = await resolveUpsertTargets(stmt.appId, stmt.keyFields, rowKeyValues, client, options, fieldTypes); stmt.values.forEach((row, rowIdx) => { const record2 = {}; stmt.fields.forEach((field, i) => { const val = row[i]; if (val.type === "CASE_VALUE") { record2[field] = { value: evalCaseWhenValue(val.expr, {}, fieldTypes.get(field)) }; } else { record2[field] = { value: toKintoneValue(val, fieldTypes.get(field)) }; } }); const id = lookupUpsertTarget(targetIndex, rowKeyValues[rowIdx]); if (id !== void 0) { toUpdate.push({ id, record: record2 }); } else { toInsert.push(record2); } }); assertValidDmlRecords( [...toInsert, ...toUpdate.map((entry) => entry.record)], stmt.fields, fieldInfos, numberPrecision ); if (options.confirm && toInsert.length + toUpdate.length > 0) { const total = toInsert.length + toUpdate.length; const ok = await options.confirm(total, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", total); } const createdIds = []; for (let i = 0; i < toInsert.length; i += 100) { const res = await client.postRecords({ app: stmt.appId, records: toInsert.slice(i, i + 100) }); createdIds.push(res.ids); } for (let i = 0; i < toUpdate.length; i += 100) { await client.putRecords({ app: stmt.appId, records: toUpdate.slice(i, i + 100) }); } return { type: "UPSERT", insertedCount: createdIds.flat().length, updatedCount: toUpdate.length }; } function buildUpsertRowKeyValues(stmt) { return stmt.values.map((row) => stmt.keyFields.map((key) => { const idx = stmt.fields.indexOf(key); if (idx === -1) throw new Error(`ON DUPLICATE \u306E\u30AD\u30FC\u300C${key}\u300D\u304C INSERT \u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093`); const val = row[idx]; return val.type === "STRING" ? val.value : val.type === "NUMBER" ? numberLiteralText(val) : val.type === "CASE_VALUE" ? evalCaseWhen(val.expr, {}) : val.elements.map((element) => element.value).join(","); })); } async function buildSubtableFieldTypeResolver(appId, typedInRefs, client, cacheContext) { if (typedInRefs.length === 0) return void 0; const fieldTypes = await getFieldTypeMap(appId, client, cacheContext); return (field) => { if (field.tableAlias !== null && field.tableAlias !== "_p") return void 0; if (field.tableAlias === "_p") return fieldTypes.get(field.field); const code = field.field.startsWith("_p.") ? field.field.slice(3) : field.field; return fieldTypes.get(code); }; } async function executeInsertSubtable(stmt, client, options, _cacheContext) { const subtableCode = stmt.subtableCode; const pidIndex = stmt.fields.indexOf("_pid"); if (pidIndex < 0) { throw new Error("\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB INSERT \u306B\u306F _pid \u304C\u5FC5\u9808\u3067\u3059"); } const parents = await fetchAll(client.getRecords, stmt.appId, "", [], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 }); const parentMap = buildParentIdMap(parents); const insertsByParent = /* @__PURE__ */ new Map(); for (const rowValues of stmt.values) { const pid = valueToString(rowValues[pidIndex]); const parent = parentMap.get(pid); if (!parent) throw new Error(`_pid=${pid} \u306E\u89AA\u30EC\u30B3\u30FC\u30C9\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`); const newRow = { value: {} }; stmt.fields.forEach((field, i) => { if (field === "_pid") return; if (field.startsWith("_")) { throw new Error(`\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB INSERT \u3067\u30B7\u30B9\u30C6\u30E0\u5217\u300C${field}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`); } newRow.value[field] = { value: valueToString(rowValues[i]) }; }); const bucket = insertsByParent.get(pid); if (bucket) bucket.push(newRow); else insertsByParent.set(pid, [newRow]); } const putCalls = []; for (const [pid, rowsToInsert] of insertsByParent.entries()) { const parent = parentMap.get(pid); const currentRows = getMutableTableRows(parent, subtableCode); const nextRows = [...currentRows, ...rowsToInsert]; putCalls.push(buildSubtablePutParams(stmt.appId, pid, getRevision(parent), subtableCode, nextRows)); } for (const p of putCalls) { await client.putRecords(p); } return { type: "INSERT", createdIds: [], insertedCount: stmt.values.length }; } async function executeUpdateSubtable(stmt, client, options, cacheContext) { const subtableCode = stmt.subtableCode; if (!hasRidCondition(stmt.where)) { throw new Error("\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u306B\u306F _rid \u6761\u4EF6\u304C\u5FC5\u9808\u3067\u3059"); } const typedInRefs = []; collectTypedInFieldRefs(stmt.where, typedInRefs); for (const assignment of stmt.assignments) { if (assignment.value.type === "CASE_VALUE") { collectCaseTypedInFieldRefs(assignment.value.expr, typedInRefs); } } const resolveFieldType = await buildSubtableFieldTypeResolver( stmt.appId, typedInRefs, client, cacheContext ); const parents = await fetchAll( client.getRecords, stmt.appId, "", [], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 } ); const expanded = expandRowsForSubtableDml(parents, subtableCode); const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType)); if (options.confirm) { const ok = await options.confirm(targets.length, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", targets.length); } const updatesByParent = /* @__PURE__ */ new Map(); for (const t of targets) { if (!t.rowId) { throw new Error("\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u5BFE\u8C61\u306B id \u672A\u63A1\u756A\u306E\u884C\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059"); } let byRid = updatesByParent.get(t.parentId); if (!byRid) { byRid = /* @__PURE__ */ new Map(); updatesByParent.set(t.parentId, byRid); } const updates = {}; for (const a of stmt.assignments) { if (a.field.startsWith("_")) { throw new Error(`\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB UPDATE \u3067\u30B7\u30B9\u30C6\u30E0\u5217\u300C${a.field}\u300D\u306F\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093`); } updates[a.field] = { value: evaluateSubtableAssignmentValue(a.value, t.flat, resolveFieldType) }; } byRid.set(t.rowId, updates); } const parentById = buildParentIdMap(parents); for (const [pid, updateMap] of updatesByParent.entries()) { const parent = parentById.get(pid); if (!parent) continue; const currentRows = getMutableTableRows(parent, subtableCode); const payloadRows = currentRows.map((row) => { const rid = row.id ?? ""; if (!rid) return row; const updates = updateMap.get(rid); if (!updates) { return { id: rid }; } return { id: rid, value: updates }; }); await client.putRecords(buildSubtablePatchPutParams(stmt.appId, pid, getRevision(parent), subtableCode, payloadRows)); } return { type: "UPDATE", updatedCount: targets.length }; } async function executeDeleteSubtable(stmt, client, options, cacheContext) { const subtableCode = stmt.subtableCode; if (!hasRidCondition(stmt.where)) { throw new Error("\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB DELETE \u306B\u306F _rid \u6761\u4EF6\u304C\u5FC5\u9808\u3067\u3059"); } const typedInRefs = []; collectTypedInFieldRefs(stmt.where, typedInRefs); const resolveFieldType = await buildSubtableFieldTypeResolver( stmt.appId, typedInRefs, client, cacheContext ); const parents = await fetchAll( client.getRecords, stmt.appId, "", [], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 } ); const expanded = expandRowsForSubtableDml(parents, subtableCode); const targets = expanded.filter((r) => evalWhere(stmt.where, r.flat, resolveFieldType)); if (options.confirm) { const ok = await options.confirm(targets.length, "DELETE"); if (!ok) throw new OperationCancelledError("DELETE", targets.length); } const byParent = /* @__PURE__ */ new Map(); for (const t of targets) { const bucket = byParent.get(t.parentId); if (bucket) bucket.push(t.rowIndex); else byParent.set(t.parentId, [t.rowIndex]); } const parentById = buildParentIdMap(parents); for (const [pid, idxs] of byParent.entries()) { const parent = parentById.get(pid); if (!parent) continue; const rows = getMutableTableRows(parent, subtableCode); const rm = new Set(idxs); const nextRows = rows.filter((_, i) => !rm.has(i)); await client.putRecords(buildSubtablePutParams(stmt.appId, pid, getRevision(parent), subtableCode, nextRows)); } return { type: "DELETE", deletedCount: targets.length }; } function buildParentIdMap(parents) { const map2 = /* @__PURE__ */ new Map(); for (const p of parents) { const pid = String(p["$id"]?.value ?? ""); if (pid) map2.set(pid, p); } return map2; } function expandRowsForSubtableDml(parents, subtableCode) { const out = []; for (const parent of parents) { const parentId = String(parent["$id"]?.value ?? ""); const parentRevision = getRevision(parent); const tableRows2 = getMutableTableRows(parent, subtableCode); for (let i = 0; i < tableRows2.length; i++) { const row = tableRows2[i]; const flat = { ...flattenSubtableSnapshotRow(row, i), _pid: parentId }; for (const [k, v] of Object.entries(parent)) { if (k === subtableCode) continue; flat[`_p.${k}`] = normalizeUnknownToString2(v?.value); } out.push({ parent, parentId, parentRevision, rowIndex: i, rowId: row.id ?? "", row, flat }); } } return out; } function getMutableTableRows(parent, subtableCode) { const raw = parent[subtableCode]?.value; if (!Array.isArray(raw)) return []; return raw; } function getRevision(parent) { const n = Number(parent["$revision"]?.value ?? 0); return Number.isFinite(n) ? n : 0; } function buildSubtablePutParams(appId, parentId, revision, subtableCode, rows) { return { app: appId, records: [ { id: Number(parentId), revision, record: { [subtableCode]: { value: rows } } } ] }; } function buildSubtablePatchPutParams(appId, parentId, revision, subtableCode, rows) { return { app: appId, records: [ { id: Number(parentId), revision, record: { [subtableCode]: { value: rows } } } ] }; } function buildSubtableReorderPutParams(appId, parentId, revision, subtableCode, rowIds) { if (rowIds.some((id) => !id)) { throw new Error("REORDER \u5BFE\u8C61\u306B id \u672A\u63A1\u756A\u306E\u884C\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059"); } return { app: appId, records: [ { id: Number(parentId), revision, record: { [subtableCode]: { value: rowIds.map((id) => ({ id })) } } } ] }; } function valueToString(value) { if (value.type === "STRING") return value.value; if (value.type === "NUMBER") return numberLiteralText(value); if (value.type === "CASE_VALUE") return evalCaseWhen(value.expr, {}); return value.elements.map((e) => e.value).join(","); } function normalizeUnknownToString2(value) { if (value === null || value === void 0) return ""; if (typeof value === "string") return value; if (typeof value === "number" || typeof value === "boolean") return String(value); try { return JSON.stringify(value); } catch { return String(value); } } function hasRidCondition(where) { switch (where.type) { case "BINARY": return where.left.type === "FIELD" && where.left.tableAlias === null && where.left.field === "_rid"; case "LOGICAL": return hasRidCondition(where.left) || hasRidCondition(where.right); case "NOT": case "GROUP": return hasRidCondition(where.expr); default: return false; } } async function executeReorder(stmt, client, options, cacheContext) { const typedInRefs = []; collectTypedInFieldRefs(stmt.where, typedInRefs); const resolveFieldType = await buildSubtableFieldTypeResolver( stmt.appId, typedInRefs, client, cacheContext ); const reorderFields = await getFieldsCached(stmt.appId, client, cacheContext); if (isConstantFalseWhere(stmt.where)) return { type: "REORDER", reorderedParentCount: 0 }; const reorderSemanticsByCode = new Map(reorderFields.map((field) => [ field.code, field.semantics ?? resolveFieldSemantics(field) ])); const resolveReorderSemantics = (field) => { if (field.field === "_idx" || field.field === "_pid" || field.field === "_rid") { return syntheticSemantics("number"); } const code = field.field.startsWith("_p.") ? field.field.slice(3) : field.field; return reorderSemanticsByCode.get(code) ?? syntheticSemantics("string"); }; const parents = await fetchAll( client.getRecords, stmt.appId, "", [], { maxRecords: options.maxRecords ?? 1e4, parallel: options.fetchParallel ?? 1 } ); const expanded = expandRowsForSubtableDml(parents, stmt.subtableCode); const targetParentIds = stmt.all ? new Set(parents.map((p) => String(p["$id"]?.value ?? "")).filter((id) => id !== "")) : new Set(expanded.filter((r) => stmt.where && evalWhere( stmt.where, r.flat, resolveFieldType, void 0, resolveReorderSemantics )).map((r) => r.parentId)); if (options.confirm) { const ok = await options.confirm(targetParentIds.size, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", targetParentIds.size); } const parentById = buildParentIdMap(parents); for (const pid of targetParentIds) { const parent = parentById.get(pid); if (!parent) continue; const rows = getMutableTableRows(parent, stmt.subtableCode); const sortable = rows.map((row, i) => ({ row, i, flat: buildFlatRowForSort(parent, stmt.subtableCode, row, i) })); sortable.sort((a, b) => compareByOrder(a.flat, b.flat, stmt.by, resolveReorderSemantics)); const orderedRowIds = sortable.map((x) => x.row.id ?? ""); await client.putRecords(buildSubtableReorderPutParams(stmt.appId, pid, getRevision(parent), stmt.subtableCode, orderedRowIds)); } return { type: "REORDER", reorderedParentCount: targetParentIds.size }; } function buildFlatRowForSort(parent, subtableCode, row, idx) { const flat = { _pid: String(parent["$id"]?.value ?? ""), _rid: row.id ?? "", _idx: String(idx) }; for (const [k, v] of Object.entries(parent)) { if (k === subtableCode) continue; flat[`_p.${k}`] = normalizeUnknownToString2(v?.value); } for (const [k, v] of Object.entries(row.value ?? {})) { flat[k] = normalizeUnknownToString2(v?.value); } return flat; } function compareByOrder(a, b, orderBy, resolveSemantics) { for (const item of orderBy) { const av = evalOrderKeyForRow(item.key, a); const bv = evalOrderKeyForRow(item.key, b); const semantics = item.key.type === "FIELD_NAME" ? resolveSemantics(aggregateFieldRef(item.key.name)) : item.key.type === "ARITH_KEY" ? syntheticSemantics("number") : stringFunctionColumnMeta(item.key.expr).semantics ?? syntheticSemantics("string"); const cmp = compareCanonicalValues(av, bv, semantics ?? syntheticSemantics("string")); if (cmp !== 0) return item.direction === "ASC" ? cmp : -cmp; } return 0; } function evalOrderKeyForRow(key, row) { switch (key.type) { case "FIELD_NAME": return row[key.name] ?? ""; case "ARITH_KEY": return String(evalArithExpr(key.expr, row)); case "FUNC_KEY": return evalStringFunc(key.expr, row); } } async function executeUpsertSelect(stmt, client, options, cacheContext, cteCache) { if (stmt.checkGroups?.length) return executeCheckedPlainDml(stmt, client, options, cacheContext, cteCache); const fieldInfos = await loadWritableTopLevelDmlFields(stmt.appId, stmt.fields, client, cacheContext); const numberPrecision = await loadNumberPrecisionForTargets(stmt.appId, stmt.fields, fieldInfos, client, cacheContext); const sourceTable = await dmlSourceMaterializer.materialize(stmt, client, options, cacheContext, cteCache, fieldInfos); const { rows, columns } = sourceTable; assertNoImportRowErrors(sourceTable); if (columns.length !== stmt.fields.length) { const emptySourceHint = columns.length === 0 && rows.length === 0 ? "\u3002\u7D50\u679C\u304C 0 \u884C\u306E\u305F\u3081\u5217\u3092\u7279\u5B9A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08SELECT * \u3092\u7A7A\u30BD\u30FC\u30B9\u306B\u4F7F\u3046\u3068\u5217\u3092\u6C7A\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002\u660E\u793A\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF09" : ""; throw new Error( `SELECT \u306E\u5217\u6570\uFF08${columns.length}\uFF09\u3068 UPSERT \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u6570\uFF08${stmt.fields.length}\uFF09\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093${emptySourceHint}` ); } for (const key of stmt.keyFields) { if (!stmt.fields.includes(key)) { throw new Error(`ON DUPLICATE \u306E\u30AD\u30FC\u300C${key}\u300D\u304C UPSERT \u30D5\u30A3\u30FC\u30EB\u30C9\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093`); } } const toInsert = []; const toUpdate = []; const fieldTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const records = rows.map((row, rowIndex) => { const record2 = {}; stmt.fields.forEach((field, i) => { if (sourceTable.importPresence && !sourceTable.importPresence[rowIndex]?.has(field)) return; const raw = row[columns[i]] ?? ""; record2[field] = { value: convertProcessRowValue(raw, fieldTypes.get(field)) }; }); return record2; }); records.forEach((record2) => assertValidDmlRecords([record2], stmt.fields.filter((field) => field in record2), fieldInfos, numberPrecision)); const rowKeyValues = records.map( (record2) => stmt.keyFields.map((key) => String(record2[key]?.value ?? "")) ); if (importSourceByDmlStatement.has(stmt)) { const numericKey = stmt.keyFields.map((key) => fieldTypes.get(key) === "NUMBER"); const sourceKeys = /* @__PURE__ */ new Set(); for (const parts of rowKeyValues) { const normalized = upsertNormalizedKey(parts, numericKey); if (sourceKeys.has(normalized)) throw new Error("ERR_KEY_DUP_SOURCE: UPSERT \u30BD\u30FC\u30B9\u5185\u3067\u30AD\u30FC\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059"); sourceKeys.add(normalized); } } const targetIndex = await resolveUpsertTargets(stmt.appId, stmt.keyFields, rowKeyValues, client, options, fieldTypes); records.forEach((record2, rowIdx) => { const id = lookupUpsertTarget(targetIndex, rowKeyValues[rowIdx]); if (id !== void 0) { toUpdate.push({ id, record: record2 }); } else { toInsert.push(record2); } }); if (options.confirm && toInsert.length + toUpdate.length > 0) { const total = toInsert.length + toUpdate.length; const ok = await options.confirm(total, "UPDATE"); if (!ok) throw new OperationCancelledError("UPDATE", total); } const createdIds = []; for (let i = 0; i < toInsert.length; i += 100) { const res = await client.postRecords({ app: stmt.appId, records: toInsert.slice(i, i + 100) }); createdIds.push(res.ids); } for (let i = 0; i < toUpdate.length; i += 100) { await client.putRecords({ app: stmt.appId, records: toUpdate.slice(i, i + 100) }); } return { type: "UPSERT", insertedCount: createdIds.flat().length, updatedCount: toUpdate.length }; } async function executeShowApps(client) { const apps = await client.getApps(); const columns = ["\u30A2\u30D7\u30EAID", "\u30A2\u30D7\u30EA\u540D", "\u8AAC\u660E"]; const rows = apps.map((a) => ({ "\u30A2\u30D7\u30EAID": String(a.appId), "\u30A2\u30D7\u30EA\u540D": a.name, "\u8AAC\u660E": a.description })); return { type: "SELECT", rows, columns, rowCount: rows.length }; } async function executeDescribe(stmt, client, cacheContext) { const fields = await getFieldsCached(stmt.appId, client, cacheContext); const columns = ["\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9", "\u30E9\u30D9\u30EB", "\u30BF\u30A4\u30D7"]; const rows = fields.map((f) => ({ "\u30D5\u30A3\u30FC\u30EB\u30C9\u30B3\u30FC\u30C9": f.code, "\u30E9\u30D9\u30EB": f.label, "\u30BF\u30A4\u30D7": f.fieldType })); return { type: "SELECT", rows, columns, rowCount: rows.length }; } function parseSql(sql, enableImport = false) { try { const tokens = new Lexer(sql).tokenize(); const stmt = new Parser(tokens, { import: enableImport }).parse(); assertApplyScope("phase15b", stmt); validateKlikeStatement(stmt); return stmt; } catch (e) { if (e instanceof LexError || e instanceof ParseError) { throw e; } throw e; } } async function resolveSubqueries(where, client, options, cacheContext, cteCache) { const tasks = []; collectSubqueryTasks(where, client, options, cacheContext, tasks, cteCache); await Promise.all(tasks); } async function resolveSelectCaseSubqueries(stmt, client, options, cacheContext, cteCache) { const tasks = []; for (const column of stmt.columns) { if (column.type !== "CASE_COL") continue; for (const branch of column.expr.branches) { tasks.push(resolveSubqueries(branch.condition, client, options, cacheContext, cteCache)); } } await Promise.all(tasks); } function runSubquery(query, client, options, cacheContext, cteCache) { if (cteCache !== void 0 && cteCache.size > 0) { return executeQueryWithCte(query, client, options, cteCache, cacheContext); } return executeSelect(query, client, options, cacheContext); } function collectSubqueryTasks(where, client, options, cacheContext, tasks, cteCache) { if (where === null) return; switch (where.type) { case "BINARY": { const right = where.right; if (right.type === "SUBQUERY_IN_LIST") { tasks.push(runSubquery(right.query, client, options, cacheContext, cteCache).then((result) => { const col = right.column ?? (result.columns[0] ?? ""); right.resolved = new Set(result.rows.map((r) => r[col] ?? "")); })); } if (right.type === "SCALAR_SUBQUERY") { tasks.push(runSubquery(right.query, client, options, cacheContext, cteCache).then((result) => { if (result.rowCount === 0) throw new Error("\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u304C\u5024\u3092\u8FD4\u3057\u307E\u305B\u3093\u3067\u3057\u305F"); if (result.rowCount > 1) throw new Error("\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u304C\u8907\u6570\u884C\u3092\u8FD4\u3057\u307E\u3057\u305F\uFF081\u884C\u306E\u307F\u8A31\u53EF\uFF09"); const col = result.columns[0] ?? ""; right.resolved = result.rows[0]?.[col] ?? ""; })); } break; } case "LOGICAL": collectSubqueryTasks(where.left, client, options, cacheContext, tasks, cteCache); collectSubqueryTasks(where.right, client, options, cacheContext, tasks, cteCache); break; case "NOT": case "GROUP": collectSubqueryTasks(where.expr, client, options, cacheContext, tasks, cteCache); break; case "EXISTS": { const node = where; tasks.push(runSubquery(node.query, client, options, cacheContext, cteCache).then((result) => { node.resolved = result.rowCount > 0; })); break; } case "BOOLEAN": break; } } async function resolveSetSubqueries(assignments, client, options, cacheContext) { for (const a of assignments) { if (a.value.type !== "SCALAR_SUBQUERY") continue; const result = await executeSelect(a.value.query, client, options, cacheContext); if (result.rowCount === 0) throw new Error(`SET \u30B5\u30D6\u30AF\u30A8\u30EA\u304C\u5024\u3092\u8FD4\u3057\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9: ${a.field}\uFF09`); if (result.rowCount > 1) throw new Error(`SET \u30B5\u30D6\u30AF\u30A8\u30EA\u304C\u8907\u6570\u884C\u3092\u8FD4\u3057\u307E\u3057\u305F\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9: ${a.field}\uFF09`); const col = result.columns[0] ?? ""; const resolved = result.rows[0]?.[col] ?? ""; a.value = { type: "STRING", value: resolved }; } } async function resolveScalarColumns(columns, client, options, cacheContext, cteCache) { const byQuery = /* @__PURE__ */ new Map(); const pending = []; for (let i = 0; i < columns.length; i++) { const col = columns[i]; if (col.type !== "SCALAR_SUBQUERY_COL") continue; const key = JSON.stringify(col.query); let promise2 = byQuery.get(key); if (!promise2) { promise2 = runSubquery(col.query, client, options, cacheContext, cteCache).then((result) => { if (result.rowCount === 0) throw new Error("\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u304C\u5024\u3092\u8FD4\u3057\u307E\u305B\u3093\u3067\u3057\u305F"); if (result.rowCount > 1) throw new Error("\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA\u304C\u8907\u6570\u884C\u3092\u8FD4\u3057\u307E\u3057\u305F\uFF081\u884C\u306E\u307F\u8A31\u53EF\uFF09"); const firstCol = result.columns[0] ?? ""; return result.rows[0]?.[firstCol] ?? ""; }); byQuery.set(key, promise2); } pending.push([i, promise2]); } const values = await Promise.all(pending.map(([, promise2]) => promise2)); const cache = /* @__PURE__ */ new Map(); pending.forEach(([i], idx) => cache.set(i, values[idx])); return cache; } var validateExplainInfo = /* @__PURE__ */ new WeakMap(); var applyParentExplainPlan = /* @__PURE__ */ new WeakMap(); async function buildExplainWhereAnalysis(query, client, cacheContext, maxRecords2 = 1e4) { const fieldApps = /* @__PURE__ */ new Set(); const processStatusApps = /* @__PURE__ */ new Set(); const numberPrecisionApps = /* @__PURE__ */ new Set(); const tracedClient = { ...client, getFields: async (appId) => { fieldApps.add(appId); return client.getFields(appId); }, getProcessStatuses: async (appId) => { processStatusApps.add(appId); return client.getProcessStatuses(appId); }, getNumberPrecision: async (appId) => { numberPrecisionApps.add(appId); return client.getNumberPrecision(appId); } }; const capabilities = /* @__PURE__ */ new Map(); const orderPlans = /* @__PURE__ */ new Map(); const seen = /* @__PURE__ */ new Set(); const visit = async (node) => { if (node === null || typeof node !== "object") return; if (seen.has(node)) return; seen.add(node); if (Array.isArray(node)) { await Promise.all(node.map(visit)); return; } const typed = node; if (typed["type"] === "SELECT") { const select = node; const physicalApps = [select.from, ...select.joins.map((join) => join.table)].filter((table) => table.cteName === null).map((table) => table.appId); const needsWhereSchema = whereNeedsFieldMetadata(select.where); if (needsWhereSchema || select.orderBy.length > 0 || select.columns.some((column) => column.type === "WINDOW_COL" && column.orderBy.length > 0)) { physicalApps.forEach((appId) => fieldApps.add(appId)); } const capability = await resolveSelectWhereCapability(select, tracedClient, cacheContext); if (capability.capability === "UNSUPPORTED") { throw new Error(`ArgumentError: WHERE predicate is unsupported (${formatWhereCapabilityFailure(capability)}).`); } capabilities.set(select, capability); if (select.orderBy.length > 0 || select.columns.some((column) => column.type === "WINDOW_COL" && column.orderBy.length > 0)) { const meta3 = await buildOrderByMetaForSelect(select, tracedClient, cacheContext); if (select.orderMode !== "KINTONE_NATIVE") { for (const semantics of meta3.semantics.values()) { if (semantics.fieldType === "STATUS" && semantics.source) { processStatusApps.add(semantics.source.appId); } } } const hasUnmaterializedSource = [select.from, ...select.joins.map((join) => join.table)].some((table) => table.cteName !== null); if (hasCanonicalOrder(select) && !hasUnmaterializedSource) { const mode = capability.capability === "EXACT_PUSHDOWN" ? resolveSelectMode(select) : "FULL_SCAN"; orderPlans.set(select, (select.orderMode === "KINTONE_NATIVE" ? planKorder : planCanonicalOrder)({ stmt: select, staticMode: mode, whereCapability: capability.capability, orderSemantics: meta3.semantics, maxRecords: maxRecords2, hasKlike: whereHasKlike(select.where) })); } } } else if (typed["type"] === "VALIDATE") { const validate = node; fieldApps.add(validate.appId); const fields = await getFieldsCached(validate.appId, tracedClient, cacheContext); const infoByCode = new Map(fields.filter((field) => !field.inSubtable).map((field) => [field.code, field])); const childCodes = new Set(fields.filter((field) => field.inSubtable).map((field) => field.code)); const targets = resolveExistingValidationTargets(validate, fields); const checks = collectCheckFieldRefs(validate.checkGroups ?? []); const whereFields = collectValidateWhereFields(validate.where); for (const ref of checks) { if (ref.field !== "$id" && !infoByCode.has(ref.field) && !childCodes.has(ref.field)) { throw customCheckParseError(`CHECK \u306E\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F APP${validate.appId} \u306B\u5B58\u5728\u3057\u307E\u305B\u3093`); } if (ref.field !== "$id" && !infoByCode.has(ref.field) && childCodes.has(ref.field)) { throw new Error(`ArgumentError: VALIDATE \u306E CHECK \u3067\u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\u3002`); } } for (const field of whereFields) { if (field !== "$id" && !infoByCode.has(field) && !childCodes.has(field)) { throw new Error(`ArgumentError: WHERE field ${field} does not exist in APP${validate.appId}.`); } if (field !== "$id" && !infoByCode.has(field) && childCodes.has(field)) { throw new Error(`ArgumentError: VALIDATE \u306E WHERE \u3067\u306F\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5B50\u30D5\u30A3\u30FC\u30EB\u30C9 ${field} \u3092\u53C2\u7167\u3067\u304D\u307E\u305B\u3093\u3002`); } } const types = new Map([...infoByCode].map(([code, field]) => [code, field.fieldType])); types.set("$id", "RECORD_NUMBER"); assertCheckComparisonTypes(validate, types); const capability = classifyWhereCapability(validate.where, (field) => field.field === "$id" ? resolveFieldSemantics({ fieldType: "__ID__" }) : infoByCode.get(field.field)?.semantics ?? (infoByCode.has(field.field) ? resolveFieldSemantics(infoByCode.get(field.field)) : void 0)); if (capability.capability === "UNSUPPORTED") { throw new Error(`ArgumentError: WHERE predicate is unsupported (${formatWhereCapabilityFailure(capability)}).`); } const fieldTypes = new Map([...infoByCode].map(([code, field]) => [code, field.fieldType])); const fieldOptions = new Map([...infoByCode.values()].flatMap((field) => field.optionOrder ? [[field.code, new Set(Object.keys(field.optionOrder))]] : [])); const prefilter = validate.where === null ? null : capability.capability === "EXACT_PUSHDOWN" ? validate.where : extractSafePushdownLeaves(validate.where, { allowUnqualifiedFields: true, fieldTypes, fieldOptions, allowKlike: false }); const needsPrecision = targets.some((target) => target.field.fieldType === "NUMBER"); if (needsPrecision) { numberPrecisionApps.add(validate.appId); await getNumberPrecisionCached(validate.appId, tracedClient, cacheContext); } validateExplainInfo.set(validate, { targetFields: targets.map((target) => target.subtableCode ? `${target.subtableCode}(${target.field.code})` : target.field.code), fetchFields: [.../* @__PURE__ */ new Set(["$id", ...targets.map((target) => target.subtableCode ?? target.field.code), ...whereFields, ...checks.map((ref) => ref.field)])], subtables: new Map([...new Set(targets.flatMap((target) => target.subtableCode ? [target.subtableCode] : []))].map((table) => [table, targets.filter((target) => target.subtableCode === table).length])), capability, prefilter, numberPrecision: needsPrecision }); } else if (typed["type"] === "UPDATE" || typed["type"] === "DELETE") { fieldApps.add(node.appId); if (typed["type"] === "UPDATE" && node.applyBlocks?.length) { const update = node; const fields = await getFieldsCached(update.appId, tracedClient, cacheContext); resolveApplyPatchMetadata(update, fields); if (usesApplyParentResidualSelection(update)) { const topLevel = fields.filter((field) => !field.inSubtable); const selectionPlan = buildApplyParentSelectionPlan(update.where, { fieldTypes: new Map(topLevel.map((field) => [field.code, field.fieldType])), fieldOptions: new Map(topLevel.flatMap((field) => field.optionOrder ? [[field.code, new Set(Object.keys(field.optionOrder))]] : [])) }); applyParentExplainPlan.set(update, selectionPlan); } } const dml = node; if (dml.type !== "UPDATE" || !usesApplyParentResidualSelection(dml)) { await assertDmlWhereCapability(dml, tracedClient, cacheContext); } } await Promise.all(Object.values(typed).map(visit)); }; await visit(query); if (typeof query === "object" && query !== null && query.type === "WITH" && canInlineSingleCte(query)) { const inlined = buildInlinedQuery(query); const capability = await resolveSelectWhereCapability(inlined, tracedClient, cacheContext); if (capability.capability === "UNSUPPORTED") { throw new Error(`ArgumentError: WHERE predicate is unsupported (${formatWhereCapabilityFailure(capability)}).`); } capabilities.set(inlined, capability); if (hasCanonicalOrder(inlined)) { const meta3 = await buildOrderByMetaForSelect(inlined, tracedClient, cacheContext); orderPlans.set(inlined, (inlined.orderMode === "KINTONE_NATIVE" ? planKorder : planCanonicalOrder)({ stmt: inlined, staticMode: capability.capability === "EXACT_PUSHDOWN" ? resolveSelectMode(inlined) : "FULL_SCAN", whereCapability: capability.capability, orderSemantics: meta3.semantics, maxRecords: maxRecords2, hasKlike: whereHasKlike(inlined.where) })); } } return { capabilities, orderPlans, fieldApps, processStatusApps, numberPrecisionApps }; } function explainMetadataLines(analysis) { return [ ...[...analysis.fieldApps].sort((a, b) => a - b).map((appId) => ` metadata API: form definition APP${appId}`), ...[...analysis.processStatusApps].sort((a, b) => a - b).map((appId) => ` metadata API: process status APP${appId}`), ...[...analysis.numberPrecisionApps].sort((a, b) => a - b).map((appId) => ` metadata API: number precision APP${appId}`) ]; } async function buildBatchExplainPlans(sql, client, injectedVariables, cacheContext = "batch-explain", maxRecords2 = 1e4, cursorMaxActive2 = 2, enableImport = false, dmlMaxRows = 100, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS) { const statements = parseSqlBatch(sql, enableImport); const analysis = analyzeBatch(statements); validateDeclaredBatchVariables(statements, injectedVariables); const variables = /* @__PURE__ */ new Map(); const plans = []; for (let i = 0; i < statements.length; i++) { const stmt = statements[i]; const planStmt = stmt.type === "SET_VARIABLE" ? stmt.expr.type === "SCALAR_SUBQUERY" ? { ...stmt, expr: resolveBatchVariableReferences(stmt.expr, variables) } : stmt : resolveBatchVariableReferences(stmt, variables); validateKlikeStatement(planStmt); const whereAnalysis = await buildExplainWhereAnalysis(planStmt, client, cacheContext, maxRecords2); const statementPlan = addCursorConcurrency(buildBatchStatementPlan( planStmt, analysis.statements[i], whereAnalysis.capabilities, whereAnalysis.orderPlans, dmlMaxRows, dmlMaxSubtableRows ), cursorMaxActive2); const metadataPlan = explainMetadataLines(whereAnalysis); plans.push({ index: i, type: analysis.statements[i].statementType, plan: statementPlan.length === 0 ? metadataPlan : [statementPlan[0], ...metadataPlan, ...statementPlan.slice(1)] }); if (stmt.type === "SET_VARIABLE" || stmt.type === "DECLARE_VARIABLE") { variables.set(stmt.name, stmt.type === "SET_VARIABLE" && stmt.expr.type === "ARRAY" ? { type: "array", elements: stmt.expr.elements.map((element) => ({ type: "string", value: element.value })) } : { type: "string", value: `@${stmt.name}` }); } } return { statementCount: statements.length, statements: plans }; } function buildBatchStatementPlan(stmt, info, capabilities, orderPlans, dmlMaxRows = 100, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS) { if (stmt.type === "CREATE_TEMP_TABLE") { return [ `CREATE TEMP TABLE ${stmt.name}`, ` scope: batch\uFF08\u30D0\u30C3\u30C1\u7D42\u4E86\u6642\u306B\u81EA\u52D5\u7834\u68C4\uFF09`, ` rows: \u5B9F\u4F53\u5316\u524D\u306E\u305F\u3081\u4E0D\u660E\uFF08\u65E2\u5B9A\u4E0A\u9650 ${TEMP_TABLE_MAX_ROWS} \u884C\u3001tempTableMaxRows \u3067\u5909\u66F4\u53EF\u3001\u8D85\u904E\u306F\u30A8\u30E9\u30FC\uFF09`, ...buildPlanForBatchQuery(stmt.query, info, capabilities, orderPlans).map((l) => ` ${l}`) ]; } if (stmt.type === "DROP_TEMP_TABLE") { return [ `DROP TEMP TABLE ${stmt.name}`, " \u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30B9\u30C8\u30A2\u306E\u89E3\u653E\u306E\u307F\uFF08kintone \u30A2\u30AF\u30BB\u30B9\u306A\u3057\uFF09" ]; } if (stmt.type === "SET_VARIABLE") { if (stmt.expr.type === "SCALAR_SUBQUERY") { const subInfo = hasTempTableRef(stmt.expr.query) ? info : { ...info, tempTablesReferenced: [] }; return [ `SET @${stmt.name} = (SELECT ...)`, " value: \u30B5\u30D6\u30AF\u30A8\u30EA\u3092\u5B9F\u884C\u6642\u306B1\u56DE\u8A55\u4FA1\uFF081\u884C1\u5217\u30FB\u30D0\u30C3\u30C1\u5185\u5B9A\u6570\u30FB\u7D50\u679C\u30E1\u30BF\u30C7\u30FC\u30BF\u306B\u306F\u975E\u516C\u958B\uFF09", " subquery:", ...buildPlanForBatchQuery(stmt.expr.query, subInfo, capabilities, orderPlans).map((l) => ` ${l}`) ]; } return [ `SET @${stmt.name} = `, " value: \u5B9F\u884C\u6642\u306B1\u56DE\u8A55\u4FA1\uFF08\u30D0\u30C3\u30C1\u5185\u5B9A\u6570\u30FB\u7D50\u679C\u30E1\u30BF\u30C7\u30FC\u30BF\u306B\u306F\u975E\u516C\u958B\uFF09" ]; } if (stmt.type === "DECLARE_VARIABLE") { return [ `DECLARE @${stmt.name} = `, " value: \u5916\u90E8\u6CE8\u5165\u304C\u3042\u308C\u3070\u63A1\u7528\u3001\u306A\u3051\u308C\u3070\u65E2\u5B9A\u5024\u3092\u5B9F\u884C\u6642\u306B1\u56DE\u8A55\u4FA1\uFF08\u5024\u306F\u975E\u516C\u958B\uFF09" ]; } if (stmt.type === "SHOW_APPS") return ["SHOW APPS\uFF08\u30A2\u30D7\u30EA\u4E00\u89A7\u306E\u53D6\u5F97\uFF09"]; if (stmt.type === "DESCRIBE") return [`DESCRIBE APP${stmt.appId}\uFF08\u30D5\u30A3\u30FC\u30EB\u30C9\u5B9A\u7FA9\u306E\u53D6\u5F97\uFF09`]; if (stmt.type === "EXPLAIN") return buildPlanForBatchQuery(stmt.query, info, capabilities, orderPlans); if (stmt.type === "ASSERT") { const lines = [ `ASSERT ${stmt.text}`, " check: \u5B9F\u884C\u6642\u306B\u6761\u4EF6\u8A55\u4FA1\uFF08\u4E0D\u6210\u7ACB\u306F AssertError \u3067\u30D0\u30C3\u30C1\u505C\u6B62\u3001\u4EE5\u964D\u306E\u6587\u306F skipped\uFF09" ]; const subqueries = [stmt.left, stmt.right, stmt.low, stmt.high].filter( (o) => o !== null && o.type === "SCALAR_SUBQUERY" ); subqueries.forEach((sq, i) => { lines.push(subqueries.length > 1 ? ` subquery[${i + 1}]:` : " subquery:"); const subInfo = hasTempTableRef(sq.query) ? info : { ...info, tempTablesReferenced: [] }; lines.push(...buildPlanForBatchQuery(sq.query, subInfo, capabilities, orderPlans).map((l) => ` ${l}`)); }); return lines; } if (stmt.type === "UPDATE" && (stmt.applyBlocks?.length ?? 0) > 0) { return buildExplainPlan(stmt, void 0, capabilities, orderPlans, dmlMaxRows, dmlMaxSubtableRows); } return buildPlanForBatchQuery(stmt, info, capabilities, orderPlans); } function hasTempTableRef(node) { if (Array.isArray(node)) return node.some(hasTempTableRef); if (node !== null && typeof node === "object") { const obj = node; const cte = obj["cteName"]; if (typeof cte === "string" && cte.startsWith("#")) return true; return Object.values(obj).some(hasTempTableRef); } return false; } function buildPlanForBatchQuery(query, info, capabilities, orderPlans) { if (info.tempTablesReferenced.length === 0) { return buildExplainPlan(query, void 0, capabilities, orderPlans); } const lines = []; if (query.type === "INSERT_SELECT") { lines.push( `INSERT INTO APP${query.appId} ... SELECT\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30BD\u30FC\u30B9\u3002\u5B9F\u884C\u6642\u306B\u4EF6\u6570\u78BA\u5B9A \u2192 dmlMaxRows \u9069\u7528\uFF09` ); } else if (query.type === "UPSERT_SELECT") { lines.push( `UPSERT INTO APP${query.appId} ... SELECT\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u30BD\u30FC\u30B9\u3002\u7167\u5408\u5F8C\u306B insert + update \u5408\u8A08\u78BA\u5B9A \u2192 dmlMaxRows \u9069\u7528\uFF09` ); } lines.push(" mode: FULL_SCAN\uFF08\u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u53C2\u7167\uFF09"); lines.push( ` temp: ${info.tempTablesReferenced.join(", ")}\uFF08\u30A4\u30F3\u30E1\u30E2\u30EA\u8D70\u67FB\u3002\u5B9F\u4F53\u5316\u524D\u306E\u305F\u3081\u884C\u6570\u4E0D\u660E\uFF09` ); const apps = info.appIds.filter( (a) => query.type !== "INSERT_SELECT" && query.type !== "UPSERT_SELECT" || a !== query.appId ); if (apps.length > 0) { lines.push(` app: ${apps.map((a) => `APP${a}`).join(", ")}`); } lines.push(" note: \u4E00\u6642\u30C6\u30FC\u30D6\u30EB\u3078\u306E WHERE \u30D7\u30C3\u30B7\u30E5\u30C0\u30A6\u30F3\u306F\u884C\u308F\u308C\u306A\u3044"); return lines; } async function executeExplain(stmt, client, cacheContext, maxRecords2, cursorMaxActive2, dmlMaxRows = 100, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS) { const analysis = await buildExplainWhereAnalysis(stmt.query, client, cacheContext, maxRecords2); const lines = [ ...explainMetadataLines(analysis), ...addCursorConcurrency( buildExplainPlan( stmt.query, void 0, analysis.capabilities, analysis.orderPlans, dmlMaxRows, dmlMaxSubtableRows, maxRecords2 ), cursorMaxActive2 ) ]; return { type: "SELECT", columns: ["plan"], rows: lines.map((line) => ({ plan: line })), rowCount: lines.length }; } function addCursorConcurrency(lines, cursorMaxActive2) { const result = []; for (const line of lines) { result.push(line); if (line.trim() === "cursor page size: 500") { const indent = line.match(/^\s*/)?.[0] ?? ""; result.push(`${indent}cursor concurrency: ${cursorMaxActive2} per domain (process-local)`); } } return result; } function buildExplainPlan(query, label, capabilities, orderPlans, dmlMaxRows = 100, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS, maxRecords2 = 1e4) { if (query.type === "UNION") return buildUnionPlan(query, capabilities, orderPlans); if (query.type === "WITH") return buildWithPlan(query, capabilities, orderPlans); if (query.type === "INSERT") return buildInsertPlan(query, label, dmlMaxRows, dmlMaxSubtableRows); if (query.type === "INSERT_SELECT") return buildInsertSelectPlan(query, label, capabilities, orderPlans); if (query.type === "UPSERT") return buildUpsertPlan(query, label, dmlMaxRows, dmlMaxSubtableRows); if (query.type === "UPSERT_SELECT") return buildUpsertSelectPlan(query, label, capabilities, orderPlans); if (query.type === "UPDATE") return buildUpdatePlan( query, label, capabilities, orderPlans, dmlMaxRows, dmlMaxSubtableRows, maxRecords2 ); if (query.type === "DELETE") return buildDeletePlan(query, label); if (query.type === "REORDER") return buildReorderPlan(query, label); if (query.type === "VALIDATE") return buildValidatePlan(query, label); if (query.type === "IMPORT") { if (query.writeMode === "UPDATE_RECORD_NUMBER") { const csvTables = query.targets?.filter((target) => target.kind === "SUBTABLE") ?? []; return [ ...label ? [label] : [], `IMPORT UPDATE INTO APP${query.appId}`, ` writeMode: UPDATE_RECORD_NUMBER`, ` source: CSV ${query.source.sourceName}`, ` keyHeader: ${query.recordNumberSourceHeader}`, ` mapping: BY_NAME`, ` parentRows: requires source load`, ` duplicate: preflight before lookup/write`, ` matched: requires lookup`, ` unmatched: requires lookup`, ` invalid: requires source load`, ` requiresLookup:true`, ` inserted: 0`, ` keyInPayload: false`, ...csvTables.length ? [ ` replaceSubtables: ${query.replaceSubtables?.join(", ") ?? "ERROR: required"}`, ` subtableRowIdPolicy: PRESERVE existing; empty/unknown add without id`, ` rowIdOwnership: owned elsewhere invalidates the parent`, ` replacementDiff: existing/input/update/add/delete/rowIdNotFound requires actual-data preflight`, ` confirmPolicy: highest warning "\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u5168\u7F6E\u63DB\u30FBN\u884C\u524A\u9664" plus per-table detail (including delete=0)` ] : [], ` disposition: ${query.validateOnly ? "VALIDATE ONLY" : query.onErrorSkip ? `ON ERROR SKIP INTO ${query.errorTable}` : "fail-fast"}`, ` gate: enabled for this parse`, ` writesKintone: ${query.validateOnly ? "false" : "true"}` ]; } const mode = query.keyFields ? "UPSERT" : "INSERT"; const hasSubtables = query.targets?.some((target) => target.kind === "SUBTABLE") === true; return [ ...label ? [label] : [], `IMPORT ${mode} INTO APP${query.appId}`, ` source: ${query.source.kind} ${query.source.sourceName}`, ` sourceFormat: ${query.source.kind}`, ` encoding: ${query.source.kind === "JSON" ? "UTF8 only" : query.source.encoding ?? "UTF8 (or loader metadata)"}`, ` mapping: ${query.source.kind === "JSON" ? "BY NAME (INTO order)" : query.source.projection ? "SELECT expressions" : query.source.mappingMode}`, ...query.source.kind === "JSON" ? [ ` duplicateKeyPolicy: reject`, ` numberLexemePolicy: preserve; JSON number accepts safe integer only`, ` precisionTargetsRequireString: true`, ` unknownKeyPolicy: reject`, ` presenceAware: true`, ...hasSubtables ? [ ` subtableRowIdPolicy: reject _rid/id; DROP IDs and renumber every input row`, ` subtableUpdatePolicy: present table replaces all rows; missing table is preserved; [] deletes all rows`, ` confirmPolicy: parent/table existing/input/add/delete detail required; delete is highest warning` ] : [] ] : [ ` header: ${query.source.hasHeader ? "HEADER" : "NO HEADER"}`, ...query.source.mappingMode === "BY_NAME" ? [ ` writtenColumns: ${query.fields.join(", ")}`, ` knownExportColumns: audit and ignore with reason/non-empty count`, ` unknownColumnPolicy: ${query.source.ignoreUnknownColumns ? "ignore with audit/non-empty count" : "ERR_IMPORT_UNKNOWN_COLUMN"}`, ` multipleValueDelimiter: LF (CRLF or LF)`, ` sourceValueMode: string-preserving`, ` roundTripNumericGuarantee: exact CSV lexeme passes strict decimal validation`, ` FILE: audit-ignore unless named in INTO (analyze error)` ] : [] ], ` sourceLimit: 10485760 bytes / ${query.fields.length} target columns`, ` key: ${query.keyFields?.join(", ") ?? "none"}`, ` checks: ${query.checkGroups?.length ?? 0}`, ` disposition: ${query.validateOnly ? "VALIDATE ONLY" : query.onErrorSkip ? `ON ERROR SKIP INTO ${query.errorTable}` : "fail-fast"}`, ` gate: enabled for this parse`, ` preflight: ${query.validateOnly && hasSubtables ? "requires actual source load at execution; this EXPLAIN is static" : "requires load"}`, ...hasSubtables ? [query.source.kind === "JSON" ? ` Phase5C: JSON mutation requires detail-capable confirmation surface` : ` Phase5D: CSV mutation requires detail-capable confirmation surface`] : [], ` writesKintone: ${query.validateOnly ? "false" : "true"}`, ` duplicateKey: preflight before lookup/write (requires load)` ]; } return buildSelectPlan(query, label, capabilities, orderPlans); } function buildValidatePlan(stmt, label) { const info = validateExplainInfo.get(stmt); const lines = []; if (label) lines.push(label); lines.push(`VALIDATE APP${stmt.appId}`); lines.push(" operation: read-only existing-record constraint audit (writesKintone=false)"); lines.push(" fetch API: GET records via offset + $id keyset paging (Cursor API unused)"); lines.push(" complete input: required (onLimit=truncate disabled)"); if (!info) { lines.push(" metadata: form definition required; number precision required for NUMBER targets"); return lines; } lines.push(` WHERE capability: ${info.capability.capability}`); lines.push(` kintone query: ${info.prefilter === null ? "(\u5168\u4EF6\u53D6\u5F97)" : whereToKintone(info.prefilter)}`); lines.push(` audit fields: ${info.targetFields.length === 0 ? "(\u306A\u3057)" : info.targetFields.join(", ")}`); lines.push(` fetch fields: ${info.fetchFields.join(", ")}`); lines.push(` mode: ${stmt.summary ? "SUMMARY" : "DETAIL"}`); if (info.subtables.size > 0) lines.push(` subtable audit: ${[...info.subtables].map(([table, count]) => `${table}(${count} fields)`).join(", ")}`); lines.push(` output schema: ${(stmt.summary ? EXISTING_VALIDATION_SUMMARY_COLUMNS : EXISTING_VALIDATION_COLUMNS).join(", ")}`); lines.push(stmt.summary ? " aggregation: record/subtable/field/code; row locator=none" : " row locator: grouped by message; $err_subrow / $err_subrow_id list all matching rows (first-occurrence order)"); lines.push(` number precision: ${info.numberPrecision ? "required" : "not required"}`); lines.push(" local checks: original WHERE re-evaluation + built-in constraints + CHECK groups"); lines.push(" records/mutation API during EXPLAIN: none; violation count unavailable"); return lines; } function buildSelectPlan(stmt, label, capabilities, orderPlans) { const whereCapability = capabilities?.get(stmt) ?? (capabilities ? [...capabilities].find(([candidate]) => JSON.stringify(candidate) === JSON.stringify(stmt))?.[1] : void 0); const orderPlan = orderPlans?.get(stmt) ?? (orderPlans ? [...orderPlans].find(([candidate]) => JSON.stringify(candidate) === JSON.stringify(stmt))?.[1] : void 0); const mode = orderPlan?.kind === "CANONICAL_LOCAL" ? "FULL_SCAN" : whereCapability && whereCapability.capability !== "EXACT_PUSHDOWN" ? "FULL_SCAN" : resolveSelectMode(stmt); const reasons = collectFullScanReasons(stmt); if (whereCapability && whereCapability.capability !== "EXACT_PUSHDOWN") { reasons.push(...whereCapability.reasons.map((reason) => reason.code)); } const lines = []; if (label) lines.push(label); lines.push(` mode: ${mode}`); if (isConstantFalseWhere(stmt.where)) { lines.push(" predicate: constant false"); lines.push(" records API access: none"); lines.push(` app: APP${stmt.from.appId} (${stmt.from.appId})`); return lines; } if (orderPlan) { lines.push(` order plan: ${orderPlan.kind}`); if (orderPlan.reasonCodes.length > 0) lines.push(` order reason: ${orderPlan.reasonCodes.join(", ")}`); if (orderPlan.kind === "KORDER_NATIVE") { lines.push(" order semantics: kintone native (not kSQL canonical)"); lines.push(" REST execution: single GET"); } else if (orderPlan.kind === "KORDER_CURSOR") { lines.push(" order semantics: kintone native (not kSQL canonical)"); lines.push(" fetch API: POST/GET/DELETE records/cursor.json"); lines.push(" cursor page size: 500"); lines.push(` scan rows: ${orderPlan.scanRows}`); } } const explainedStmt = orderPlan && !orderPlan.requiresCompleteInput ? { ...stmt, orderBy: [] } : stmt; const completeReasons = completeInputReasons(explainedStmt); if (orderPlan?.requiresCompleteInput) completeReasons.add("LOCAL_ORDER"); if (completeReasons.size > 0) { lines.push(" complete input: required (onLimit=truncate disabled)"); lines.push(` complete input reason: ${[...completeReasons].join(", ")}`); lines.push(" onLimit=truncate: disabled"); } if (mode === "FULL_SCAN" && reasons.length > 0) { lines.push(` reason: ${reasons.join(", ")}`); } if (mode === "SIMPLE") { const params = selectToKintoneParams(orderPlan?.kind === "CANONICAL_REST_TOP_N" ? withCanonicalRestTie(stmt) : stmt); lines.push(` app: APP${stmt.from.appId} (${stmt.from.appId})`); const displayedQuery = orderPlan?.kind === "KORDER_CURSOR" ? buildKorderCursorQuery(stmt) : params.query; lines.push(` kintone query: ${displayedQuery || "(\u306A\u3057)"}`); lines.push(` fields: ${params.fields.length === 0 ? "(\u5168\u30D5\u30A3\u30FC\u30EB\u30C9)" : params.fields.join(", ")}`); } else { const pushdownPlan = buildKlikePushdownPlan(stmt); const mainFields = selectToFetchAllFields(stmt, stmt.from); const mainAliasStr = stmt.from.alias ? ` AS ${stmt.from.alias}` : ""; const mainPushDown = pushdownPlan.mainCondition; const mainCandidate = extractMainTypedPushdownCandidate(stmt); const exactOriginalWhere = stmt.joins.length === 0 && whereCapability?.capability === "EXACT_PUSHDOWN" && stmt.where !== null && !whereRequiresJsEval(stmt.where) ? whereToKintone(stmt.where) : ""; const mainQ = mainPushDown !== null ? whereToKintone(mainPushDown) : exactOriginalWhere || "(\u5168\u4EF6\u53D6\u5F97)"; lines.push(` app: APP${stmt.from.appId}${mainAliasStr} (${stmt.from.appId})`); lines.push(` kintone query: ${mainQ}`); if (mainCandidate !== null) { lines.push(` pushdown candidate: ${whereToKintone(mainCandidate)}\uFF08\u5B9F\u884C\u6642\u306E\u578B\u30FB\u5B9F\u5728\u78BA\u8A8D\u5F85\u3061\uFF09`); } lines.push(` fields: ${mainFields.length === 0 ? "(\u5168\u30D5\u30A3\u30FC\u30EB\u30C9)" : mainFields.join(", ")}`); for (const join of stmt.joins) { const joinFields = selectToFetchAllFields(stmt, join.table); const joinAliasStr = join.table.alias ? ` AS ${join.table.alias}` : ""; const joinType = join.type === "INNER" ? "JOIN" : `${join.type} JOIN`; const joinPushDown = join.table.alias ? pushdownPlan.joinConditions.get(join.table.alias) ?? null : null; const joinCandidate = join.table.alias && !join.table.subtableCode && join.table.cteName === null && stmt.where ? extractTypedPushdownCandidates(stmt.where, { tableAlias: join.table.alias }) : null; const joinQ = joinPushDown !== null ? whereToKintone(joinPushDown) : "(\u5168\u4EF6\u53D6\u5F97)"; lines.push(` ${joinType}: APP${join.table.appId}${joinAliasStr} (${join.table.appId})`); lines.push(` kintone query: ${joinQ}`); if (joinCandidate !== null) { lines.push(` pushdown candidate: ${whereToKintone(joinCandidate)}\uFF08\u5B9F\u884C\u6642\u306E\u578B\u30FB\u5B9F\u5728\u78BA\u8A8D\u5F85\u3061\uFF09`); } lines.push(` fields: ${joinFields.length === 0 ? "(\u5168\u30D5\u30A3\u30FC\u30EB\u30C9)" : joinFields.join(", ")}`); } } lines.push(...collectSubqueryPlans(stmt, capabilities, orderPlans)); return lines; } function buildUnionPlan(stmt, capabilities, orderPlans) { const selects = []; const collect = (u) => { if (u.type === "SELECT") { selects.push(u); return; } collect(u.left); selects.push(u.right); }; collect(stmt); const lines = []; selects.forEach((sel, i) => { if (i > 0) lines.push(""); lines.push(...buildSelectPlan(sel, `[union:${i + 1}]`, capabilities, orderPlans)); }); return lines; } function buildWithPlan(stmt, capabilities, orderPlans) { const lines = []; for (const cte of stmt.ctes) { if (cte.query.type === "SELECT") { lines.push(...buildSelectPlan(cte.query, `[cte: ${cte.name}]`, capabilities, orderPlans)); lines.push(""); } } if (stmt.query.type === "SELECT" || stmt.query.type === "UNION") { lines.push(...buildExplainPlan(stmt.query, "[main]", capabilities, orderPlans)); } if (canInlineSingleCte(stmt)) { lines.push(""); const inlined = buildInlinedQuery(stmt); lines.push(...buildSelectPlan(inlined, "[effective: inlined CTE]", capabilities, orderPlans)); } return lines; } function collectFullScanReasons(stmt) { const r = []; if (stmt.from.subtableCode || stmt.joins.some((j) => j.table.subtableCode)) r.push("\u30B5\u30D6\u30C6\u30FC\u30D6\u30EB\u4EEE\u60F3\u30C6\u30FC\u30D6\u30EB"); if (stmt.joins.length > 0) r.push("JOIN \u3042\u308A"); if (stmt.groupBy.length > 0) r.push("GROUP BY \u3042\u308A"); if (stmt.distinct) r.push("DISTINCT \u3042\u308A"); if (stmt.columns.some((c) => c.type === "AGGREGATE" || c.type === "ARITH_AGG_COL")) r.push("\u96C6\u8A08\u95A2\u6570\uFF08COUNT / SUM \u7B49\uFF09\u3042\u308A"); if (stmt.columns.some((c) => c.type === "WINDOW_COL")) r.push("\u30A6\u30A3\u30F3\u30C9\u30A6\u95A2\u6570\u3042\u308A"); if (stmt.columns.some((c) => c.type === "SCALAR_SUBQUERY_COL")) r.push("SELECT \u5217\u306B\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA"); if (whereRequiresJsEval(stmt.where)) r.push("WHERE \u53E5\u306B JS \u8A55\u4FA1\u304C\u5FC5\u8981\u306A\u5F0F"); if (whereHasLike(stmt.where)) r.push("LIKE \u306F\u5E38\u306B JS \u8A55\u4FA1\u306E\u305F\u3081\u5168\u4EF6\u53D6\u5F97"); if (stmt.orderBy.some((o) => o.key.type !== "FIELD_NAME")) r.push("ORDER BY \u306B\u5F0F"); return r; } function collectSubqueryPlans(stmt, capabilities, orderPlans) { const lines = []; let idx = 1; const visitWhere = (w) => { if (!w) return; switch (w.type) { case "BINARY": if (w.right.type === "SCALAR_SUBQUERY") { lines.push(""); lines.push(...buildSelectPlan(w.right.query, `[subquery:${idx++}]`, capabilities, orderPlans)); } if (w.right.type === "SUBQUERY_IN_LIST") { lines.push(""); lines.push(...buildSelectPlan(w.right.query, `[subquery:${idx++}]`, capabilities, orderPlans)); } break; case "EXISTS": lines.push(""); lines.push(...buildSelectPlan(w.query, `[subquery:${idx++}]`, capabilities, orderPlans)); break; case "LOGICAL": visitWhere(w.left); visitWhere(w.right); break; case "NOT": case "GROUP": visitWhere(w.expr); break; case "NULL_CHECK": break; case "BOOLEAN": break; } }; visitWhere(stmt.where); for (const col of stmt.columns) { if (col.type === "SCALAR_SUBQUERY_COL") { lines.push(""); lines.push(...buildSelectPlan(col.query, `[subquery:${idx++}]`, capabilities, orderPlans)); } } if (stmt.having) visitWhere(stmt.having); return lines; } function buildInsertPlan(stmt, label, dmlMaxRows = DEFAULT_APPLY_MAX_ROWS, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS) { const totalRows = stmt.values.length; const batchCount = Math.ceil(totalRows / 100); const lines = []; if (label) lines.push(label); lines.push(` [INSERT]`); lines.push(` target: APP${stmt.appId} (${stmt.appId})`); lines.push(` records: ${totalRows} \u4EF6\uFF08\u30D0\u30C3\u30C1 ${batchCount} \u56DE \xD7 \u6700\u5927 100 \u4EF6\uFF09`); lines.push(` api: POST /k/v1/records.json \xD7 ${batchCount}`); lines.push(` fields: ${stmt.fields.join(", ")}`); return stmt.applyBlocks?.length ? [...lines, ...formatStaticApplyDiagnostic(buildStaticApplyDiagnostic(stmt, dmlMaxRows, dmlMaxSubtableRows))] : lines; } function buildInsertSelectPlan(stmt, label, capabilities, orderPlans) { const lines = []; if (label) lines.push(label); lines.push(` [INSERT SELECT]`); lines.push(` target: APP${stmt.appId} (${stmt.appId})`); lines.push(` fields: ${stmt.fields.join(", ")}`); lines.push(` api: POST /k/v1/records.json\uFF08\u4EF6\u6570\u306F SELECT \u7D50\u679C\u306B\u4F9D\u5B58\u3001100 \u4EF6\u3054\u3068\u306B\u30D0\u30C3\u30C1\uFF09`); lines.push(""); lines.push(...buildSelectPlan(stmt.select, "[source SELECT]", capabilities, orderPlans)); return lines; } function buildUpdatePlan(stmt, label, capabilities, orderPlans, dmlMaxRows = 100, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS, maxRecords2 = 1e4) { if (stmt.applyBlocks?.length) { return buildUpdateApplyPlan(stmt, label, dmlMaxRows, dmlMaxSubtableRows, maxRecords2); } const isArith = hasArithAssignment(stmt); const isStringFunc = stmt.assignments.some((a) => a.value.type === "STRING_FUNC"); const isRowDependent = hasRowDependentAssignment(stmt); const isSubq = stmt.assignments.some((a) => a.value.type === "SCALAR_SUBQUERY"); const lines = []; if (label) lines.push(label); lines.push(stmt.from ? ` [UPDATE FROM]` : ` [UPDATE]`); lines.push(` target: APP${stmt.appId} (${stmt.appId})`); if (stmt.from) { const source = stmt.from.cteName ?? `APP${stmt.from.appId}`; lines.push(` source: ${source} AS ${stmt.from.alias}`); lines.push(` join: APP${stmt.appId}.${stmt.from.targetJoinField} = ${stmt.from.alias}.${stmt.from.joinKeyField}`); lines.push(` target filter: ${stmt.from.targetFilter ? safeWhereToKintone(stmt.from.targetFilter) : "(none)"}`); } else { lines.push(` kintone query: ${safeWhereToKintone(stmt.where)}`); } if (!stmt.subtableCode) { lines.push(" selection: exact native pushdown; JS residual none"); lines.push(" search abort: DML fail-closed (SearchAbortedError; mutation 0)"); } lines.push(isConstantFalseWhere(stmt.where) ? " api: metadata validation only (records API access: none)" : ` api: GET /k/v1/records.json \u2192 PUT /k/v1/records.json`); const setTypes = []; if (isArith) setTypes.push("\u7B97\u8853 SET\uFF08\u73FE\u5728\u5024\u3092\u53D6\u5F97\u3057\u3066\u8A08\u7B97\uFF09"); if (isStringFunc) setTypes.push("\u6587\u5B57\u5217\u95A2\u6570 SET\uFF08\u73FE\u5728\u5024\u3092\u53D6\u5F97\u3057\u3066\u8A55\u4FA1\uFF09"); if (isSubq) setTypes.push("\u30B9\u30AB\u30E9\u30FC\u30B5\u30D6\u30AF\u30A8\u30EA SET"); if (!isRowDependent && !isSubq) setTypes.push("\u5358\u7D14 SET"); lines.push(` set type: ${setTypes.join(", ")}`); if (isRowDependent) { const refFields = collectArithRefFields(stmt); if (refFields.length > 0) { lines.push(` ref fields: ${refFields.join(", ")}\uFF08GET \u306B\u542B\u3081\u308B\uFF09`); } } lines.push(` set fields:`); for (const a of stmt.assignments) { lines.push(` ${formatAssignment(a)}`); } for (const a of stmt.assignments) { if (a.value.type === "SCALAR_SUBQUERY") { lines.push(""); lines.push(...buildSelectPlan(a.value.query, `[subquery: ${a.field}]`, capabilities, orderPlans)); } } return lines; } function buildUpdateApplyPlan(stmt, label, dmlMaxRows, dmlMaxSubtableRows, maxRecords2) { const diagnostic2 = buildStaticApplyDiagnostic(stmt, dmlMaxRows, dmlMaxSubtableRows); const branch = diagnostic2.branches[0]; const blocks = stmt.applyBlocks; const operations = blocks.flatMap((block) => [...block.operations]); const selectorKinds = operations.map((operation) => { if (operation.kind === "APPEND") return "APPEND"; if (operation.kind === "ADD" || operation.kind === "REMOVE_VALUE") return "VALUE_LITERAL"; if (operation.selector.kind === "ALL_ROWS") return "ALL_ROWS"; const where = operation.selector.where; return where.type === "BINARY" && where.op === "=" && where.left.type === "FIELD" && where.left.tableAlias === null && where.left.field === "_rid" ? "_rid" : "SAFE_PREDICATE"; }); const operationKinds = [...new Set(branch.targets.flatMap((target) => target.operations.map((operation) => operation.kind)))]; const hasRemove = operationKinds.includes("REMOVE"); const selectionPlan = applyParentExplainPlan.get(stmt); const selectionLines = selectionPlan ? [ "parent selection: safe prefilter + JS residual evaluation", `kintone prefilter: ${selectionPlan.prefilter === null ? "(none; empty query)" : whereToKintone(selectionPlan.prefilter)}`, "JS residual: original parent WHERE", `applied KLIKE: ${selectionPlan.appliedKlikes.size}`, `unapplied KLIKE: ${selectionPlan.unappliedKlikes.length}${selectionPlan.unappliedKlikes.length > 0 ? " (unsupported: cannot be fully applied to native query)" : ""}`, `candidate limit: maxRecords=${maxRecords2}, onLimit=error, stopAfter=none`, `target guard: dmlMaxRows=${dmlMaxRows} after JS residual evaluation`, "search abort: DML fail-closed (B7-P3; all surfaces, no surface gate)" ] : []; return [ ...label ? [label] : [], "statement: UPDATE APPLY", `target app: APP${stmt.appId}`, `parent selector: ${safeWhereToKintone(stmt.where)}`, `parent cardinality: ${isSinglePositiveRecordIdWhere(stmt.where) ? "single" : "multiple"}`, ...selectionLines, `apply target: ${branch.targets.map((target) => `${target.field} (${target.targetKind})`).join(" | ")}`, `operations: ${operationKinds.join(" | ")}`, `selector: ${selectorKinds.join(" | ")}`, "snapshot evaluation: yes", "inserted rows visible: no", "revision guard: required", "revision: unknown (records API not called)", `payload preservation: row ids=yes, row order=yes, unpatched cells=yes, remove tables=${hasRemove ? "FULL_SURVIVORS" : "none"}`, "post-image validation: required (B43 equivalent)", "parent rows: unknown (records API not called)", "matched subtable rows: unknown (records API not called)", "validation errors: unknown (records API not called)", `deleted rows: ${hasRemove ? "unknown (records API not called)" : "0 (static without REMOVE)"}`, `dmlMaxRows: ${dmlMaxRows}`, `dmlMaxSubtableRows: ${dmlMaxSubtableRows}`, "MCP mutation: disabled in v1", ...formatStaticApplyDiagnostic(diagnostic2) ]; } function buildDeletePlan(stmt, label) { const lines = []; if (label) lines.push(label); lines.push(` [DELETE]`); lines.push(` target: APP${stmt.appId} (${stmt.appId})`); lines.push(` kintone query: ${safeWhereToKintone(stmt.where)}`); if (!stmt.subtableCode) { lines.push(" selection: exact native pushdown; JS residual none"); lines.push(" search abort: DML fail-closed (SearchAbortedError; mutation 0)"); } lines.push(isConstantFalseWhere(stmt.where) ? " api: metadata validation only (records API access: none)" : ` api: GET /k/v1/records.json \u2192 DELETE /k/v1/records.json`); return lines; } function buildUpsertPlan(stmt, label, dmlMaxRows = DEFAULT_APPLY_MAX_ROWS, dmlMaxSubtableRows = DEFAULT_APPLY_MAX_SUBTABLE_ROWS) { const totalRows = stmt.values.length; const batchCount = Math.ceil(totalRows / 100); const lines = [ ...label ? [label] : [], ` [UPSERT]`, ` target: APP${stmt.appId} (${stmt.appId})`, ` records: ${totalRows} \u4EF6\uFF08\u30D0\u30C3\u30C1 ${batchCount} \u56DE \xD7 \u6700\u5927 100 \u4EF6\uFF09`, ` key fields: ${stmt.keyFields.join(", ")}`, ` fields: ${stmt.fields.join(", ")}`, ` api: GET /k/v1/records.json\uFF08\u91CD\u8907\u5224\u5B9A\uFF09\u2192 POST \u307E\u305F\u306F PUT /k/v1/records.json \xD7 ${batchCount}` ]; return stmt.onInsertApplyBlocks?.length || stmt.onUpdateApplyBlocks?.length ? [...lines, ...formatStaticApplyDiagnostic(buildStaticApplyDiagnostic(stmt, dmlMaxRows, dmlMaxSubtableRows))] : lines; } function formatStaticApplyDiagnostic(diagnostic2) { const lines = [ `apply diagnostic: ${diagnostic2.statementKind}`, `non-transactional: ${diagnostic2.nonTransactional}`, `partial success: ${diagnostic2.partialSuccess.possible ? "possible" : "none"}` ]; for (const branch of diagnostic2.branches) { lines.push( `apply branch: ${branch.branch}`, ` parent rows: ${branch.parentRows === null ? "unknown (records API not called)" : branch.parentRows}`, ` chunks: ${branch.chunk.plannedChunks === null ? "unknown" : branch.chunk.plannedChunks} \xD7 max ${branch.chunk.size}`, ` revision guard: ${branch.guards.revisionRequired ? "required" : "not required"}` ); for (const target of branch.targets) { lines.push( ` target: ${target.field} (${target.targetKind})`, ` operations: ${target.operations.map((operation) => `${operation.kind}=${operation.count === null ? "unknown" : operation.count}`).join(" | ")}`, ` changed count: ${target.changedCount === null ? "unknown" : target.changedCount}` ); } } lines.push("records API: 0", "mutation API: 0"); return lines; } function buildUpsertSelectPlan(stmt, label, capabilities, orderPlans) { const lines = [ ...label ? [label] : [], ` [UPSERT SELECT]`, ` target: APP${stmt.appId} (${stmt.appId})`, ` key fields: ${stmt.keyFields.join(", ")}`, ` fields: ${stmt.fields.join(", ")}`, ` api: GET /k/v1/records.json\uFF08\u91CD\u8907\u5224\u5B9A\uFF09\u2192 POST \u307E\u305F\u306F PUT /k/v1/records.json\uFF08100 \u4EF6\u3054\u3068\u306B\u30D0\u30C3\u30C1\uFF09`, `` ]; lines.push(...buildSelectPlan(stmt.select, "[source SELECT]", capabilities, orderPlans)); return lines; } function buildReorderPlan(stmt, label) { const target = `APP${stmt.appId}$${stmt.subtableCode}`; const scope = stmt.all ? "\u5168\u89AA\u30EC\u30B3\u30FC\u30C9\u5BFE\u8C61" : "WHERE \u6761\u4EF6\u306B\u4E00\u81F4\u3059\u308B\u89AA\u30EC\u30B3\u30FC\u30C9\u5BFE\u8C61"; const byStr = stmt.by.map(formatOrderByItem).join(", "); const lines = [ ...label ? [label] : [], ` [REORDER]`, ` target: APP${stmt.appId} (${stmt.appId})`, ` table: ${target}`, ` scope: ${scope}`, ` by: ${byStr}`, isConstantFalseWhere(stmt.where) ? ` api: metadata validation only (records API access: none)` : ` api: GET /k/v1/records.json\uFF08\u884C ID \u53D6\u5F97\uFF09\u2192 PUT /k/v1/records.json\uFF08id \u914D\u5217\u306E\u307F\u9001\u4FE1\uFF09` ]; if (!stmt.all && stmt.where) { lines.splice(5, 0, ` where: ${safeWhereToKintone(stmt.where)}`); } return lines; } function formatOrderByItem(item) { const key = item.key.type === "FIELD_NAME" ? item.key.name : "(\u5F0F)"; return `${key} ${item.direction}`; } function safeWhereToKintone(where) { if (where.type === "BOOLEAN") return where.value ? "TRUE" : "FALSE (constant)"; try { return whereToKintone(where); } catch { return "(JS \u8A55\u4FA1\u304C\u5FC5\u8981\u306A\u305F\u3081 kintone \u30AF\u30A8\u30EA\u306B\u5909\u63DB\u4E0D\u53EF)"; } } function collectArithRefFields(stmt) { const refs = /* @__PURE__ */ new Set(); for (const { value } of stmt.assignments) { if (value.type === "ARITH") collectArithNodeRefs(value, refs); if (value.type === "STRING_FUNC") collectArithNodeRefs(value, refs); if (value.type === "SCALAR_ARITH" || value.type === "CONCAT_OP") collectScalarNodeRefs(value, refs); } return [...refs]; } function collectArithNodeRefs(node, out) { if (node.type === "FIELD_REF") { out.add(node.field); return; } if (node.type === "ARITH") { collectArithNodeRefs(node.left, out); collectArithNodeRefs(node.right, out); } if (node.type === "STRING_FUNC") { for (const arg of node.args) { if (arg.type !== "AGG_REF" && arg.type !== "AGG_ARITH") collectScalarNodeRefs(arg, out); } } } async function resolveUpdateFromCheckScope(stmt, from, client, cacheContext, tempTables) { const refs = checkRefs(stmt); const targetTypes = await getFieldTypeMap(stmt.appId, client, cacheContext); const sourceTableName = from.cteName; const sourceTypes = sourceTableName !== null ? new Map((tempTables?.get(sourceTableName)?.columns ?? []).map((column) => [ column, tempTables?.get(sourceTableName)?.columnMeta?.get(column)?.fieldType ?? (tempTables?.get(sourceTableName)?.columnMeta?.get(column)?.semantics?.compareMode === "number" ? "NUMBER" : "SINGLE_LINE_TEXT") ])) : await getFieldTypeMap(from.appId, client, cacheContext); const targetFields = /* @__PURE__ */ new Set(); const sourceFields = /* @__PURE__ */ new Set(); for (const ref of refs) { if (ref.tableAlias !== null) { if (ref.tableAlias.toLowerCase() === `app${stmt.appId}`.toLowerCase()) { if (ref.field !== "$id" && !targetTypes.has(ref.field)) throw customCheckParseError(`CHECK \u306E\u30BF\u30FC\u30B2\u30C3\u30C8\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F\u5B58\u5728\u3057\u307E\u305B\u3093`); targetFields.add(ref.field); } else if (ref.tableAlias.toLowerCase() === from.alias.toLowerCase()) { if (ref.field !== "$id" && !sourceTypes.has(ref.field)) throw customCheckParseError(`CHECK \u306E\u30BD\u30FC\u30B9\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F\u5B58\u5728\u3057\u307E\u305B\u3093`); sourceFields.add(ref.field); } else { throw customCheckParseError(`CHECK \u306E\u4FEE\u98FE\u5B50 ${ref.tableAlias} \u306F\u66F4\u65B0\u5148\u307E\u305F\u306F FROM alias \u3067\u306F\u3042\u308A\u307E\u305B\u3093`); } continue; } const inTarget = ref.field === "$id" || targetTypes.has(ref.field); const inSource = ref.field === "$id" || sourceTypes.has(ref.field); if (!inTarget) { throw customCheckParseError(`UPDATE FROM \u306E CHECK \u3067\u306F\u30BD\u30FC\u30B9\u5217 ${ref.field} \u3092\u4FEE\u98FE\u3057\u3066\u304F\u3060\u3055\u3044`); } if (inSource) { throw customCheckParseError(`UPDATE FROM \u306E CHECK \u306E\u975E\u4FEE\u98FE\u30D5\u30A3\u30FC\u30EB\u30C9 ${ref.field} \u306F\u66D6\u6627\u3067\u3059`); } targetFields.add(ref.field); } const evaluationTypes = /* @__PURE__ */ new Map(); for (const [field, type] of targetTypes) { evaluationTypes.set(field, type); evaluationTypes.set(`APP${stmt.appId}.${field}`, type); } evaluationTypes.set("$id", "RECORD_NUMBER"); evaluationTypes.set(`APP${stmt.appId}.$id`, "RECORD_NUMBER"); for (const [field, type] of sourceTypes) evaluationTypes.set(`${from.alias}.${field}`, type); return { targetFields: [...targetFields], sourceFields: [...sourceFields], evaluationTypes }; } function updateFromEvaluationRow(pair, appId, sourceAlias) { if (!pair) return {}; const target = flatten(pair.target, null); return Object.fromEntries([ ...Object.entries(target), ...Object.entries(target).map(([field, value]) => [`APP${appId}.${field}`, value]), ...Object.entries(pair.source).map(([field, value]) => [`${sourceAlias}.${field}`, value]) ]); } function collectScalarNodeRefs(node, out) { if (node.type === "FIELD") { out.add(node.tableAlias ? `${node.tableAlias}.${node.field}` : node.field); return; } if (node.type === "STRING_FUNC") { for (const arg of node.args) if (arg.type !== "AGG_REF" && arg.type !== "AGG_ARITH") collectScalarNodeRefs(arg, out); return; } if (node.type === "SCALAR_ARITH" || node.type === "CONCAT_OP") { collectScalarNodeRefs(node.left, out); collectScalarNodeRefs(node.right, out); } } function formatAssignment(a) { const v = a.value; if (v.type === "STRING") return `${a.field} = '${v.value}'`; if (v.type === "NUMBER") return `${a.field} = ${v.value}`; if (v.type === "ARITH") return `${a.field} = ${formatArithExprStr(v)}`; if (v.type === "CASE_VALUE") return `${a.field} = CASE WHEN ...`; if (v.type === "STRING_FUNC") return `${a.field} = ${v.func}(...)`; if (v.type === "SCALAR_SUBQUERY") return `${a.field} = (SELECT ...)`; if (v.type === "SOURCE_FIELD") return `${a.field} = ${v.alias}.${v.field}`; return `${a.field} = (${v.type})`; } function formatArithExprStr(expr) { return `${formatArithNodeStr(expr.left)} ${expr.op} ${formatArithNodeStr(expr.right)}`; } function formatArithNodeStr(node) { if (node.type === "FIELD_REF") return node.field; if (node.type === "NUMBER") return numberLiteralText(node); if (node.type === "ARITH") return `(${formatArithExprStr(node)})`; return "..."; } var OperationCancelledError = class extends Error { constructor(operation, affectedCount) { super( `${operation} \u3092\u30AD\u30E3\u30F3\u30BB\u30EB\u3057\u307E\u3057\u305F\uFF08\u5BFE\u8C61: ${affectedCount} \u4EF6\uFF09` ); this.operation = operation; this.affectedCount = affectedCount; this.name = "OperationCancelledError"; } }; // src/core/sql.ts init_define_KSQL_DOCS(); function parseSqlStatement(sql, capabilities = {}) { const tokens = new Lexer(sql).tokenize(); const stmt = new Parser(tokens, capabilities).parse(); validateKlikeStatement(stmt); return stmt; } function parseSqlStatements(sql, capabilities = {}) { const tokens = new Lexer(sql).tokenize(); const statements = new Parser(tokens, capabilities).parseStatements(); statements.forEach(validateKlikeStatement); return statements; } // src/core/displayFormat.ts init_define_KSQL_DOCS(); // src/output/batchEnvelope.ts init_define_KSQL_DOCS(); function toMutationSummary(result) { if (result.type === "INSERT") { return { insertedCount: result.insertedCount, createdIds: result.createdIds, ...result.successfulChunks !== void 0 ? { successfulChunks: result.successfulChunks } : {}, ...result.successfulParents !== void 0 ? { successfulParents: result.successfulParents } : {}, ...result.nonTransactional !== void 0 ? { nonTransactional: result.nonTransactional } : {}, ...result.diagnostic !== void 0 ? { diagnostic: result.diagnostic } : {}, ...result.affectedRows !== void 0 ? { affectedRows: result.affectedRows } : {}, ...result.skippedRows !== void 0 ? { skippedRows: result.skippedRows } : {}, ...result.rejectLimit !== void 0 ? { rejectLimit: result.rejectLimit } : {}, ...result.errTable !== void 0 ? { errTable: result.errTable } : {} }; } if (result.type === "UPDATE") return { updatedCount: result.updatedCount, ...result.successfulChunks !== void 0 ? { successfulChunks: result.successfulChunks } : {}, ...result.successfulParents !== void 0 ? { successfulParents: result.successfulParents } : {}, ...result.nonTransactional !== void 0 ? { nonTransactional: result.nonTransactional } : {}, ...result.diagnostic !== void 0 ? { diagnostic: result.diagnostic } : {}, ...result.affectedRows !== void 0 ? { affectedRows: result.affectedRows } : {}, ...result.skippedRows !== void 0 ? { skippedRows: result.skippedRows } : {}, ...result.rejectLimit !== void 0 ? { rejectLimit: result.rejectLimit } : {}, ...result.errTable !== void 0 ? { errTable: result.errTable } : {} }; if (result.type === "DELETE") return { deletedCount: result.deletedCount }; if (result.type === "UPSERT") { return { insertedCount: result.insertedCount, updatedCount: result.updatedCount, ...result.successfulChunks !== void 0 ? { successfulChunks: result.successfulChunks } : {}, ...result.successfulParents !== void 0 ? { successfulParents: result.successfulParents } : {}, ...result.successfulInsertChunks !== void 0 ? { successfulInsertChunks: result.successfulInsertChunks } : {}, ...result.successfulUpdateChunks !== void 0 ? { successfulUpdateChunks: result.successfulUpdateChunks } : {}, ...result.nonTransactional !== void 0 ? { nonTransactional: result.nonTransactional } : {}, ...result.diagnostic !== void 0 ? { diagnostic: result.diagnostic } : {}, ...result.affectedRows !== void 0 ? { affectedRows: result.affectedRows } : {}, ...result.skippedRows !== void 0 ? { skippedRows: result.skippedRows } : {}, ...result.rejectLimit !== void 0 ? { rejectLimit: result.rejectLimit } : {}, ...result.errTable !== void 0 ? { errTable: result.errTable } : {} }; } return { reorderedParentCount: result.reorderedParentCount }; } function buildBatchEnvelope(batch, options = {}) { const { maxTotalRecords } = options; const results = []; let totalRows = 0; const statements = batch.statements.map((s) => { const entry = { index: s.index, type: s.type, status: s.status }; if (s.status === "error" && s.error) entry.error = s.error; if (s.status === "skipped" && s.skippedReason) entry.skippedReason = s.skippedReason; if (s.tempTable !== void 0) entry.tempTable = s.tempTable; if (s.rowCount !== void 0) entry.rowCount = s.rowCount; if (s.status === "success" && s.result?.type === "SELECT") { totalRows += s.result.rowCount; if (maxTotalRecords !== void 0 && totalRows > maxTotalRecords) { throw new Error( `ArgumentError: batch total rows (${totalRows}) exceed maxTotalRecords (${maxTotalRecords}).` ); } entry.resultIndex = results.length; results.push({ type: "SELECT", columns: s.result.columns, rows: s.result.rows, rowCount: s.result.rowCount, warnings: s.result.warnings ?? [], ...s.result.validateStats ? { validateStats: s.result.validateStats } : {} }); } else if (s.result?.type === "VALIDATION") { totalRows += s.result.errorCount; if (maxTotalRecords !== void 0 && totalRows > maxTotalRecords) { throw new Error(`ArgumentError: batch total rows (${totalRows}) exceed maxTotalRecords (${maxTotalRecords}).`); } entry.resultIndex = results.length; results.push({ type: "VALIDATION", columns: s.result.columns, rows: s.result.errors, rowCount: s.result.errorCount, warnings: [], operation: s.result.operation, validatedRows: s.result.validatedRows, validRows: s.result.validRows, invalidRows: s.result.invalidRows, errorCount: s.result.errorCount, ...s.result.errTable ? { errTable: s.result.errTable } : {}, ...s.result.importDetail ? { importDetail: s.result.importDetail } : {}, ...s.result.apply ? { apply: s.result.apply } : {}, ...s.result.guards ? { guards: s.result.guards } : {}, ...s.result.applyBranches ? { applyBranches: s.result.applyBranches } : {}, ...s.result.deletedRows ? { deletedRows: s.result.deletedRows } : {}, ...s.result.diagnostic ? { diagnostic: s.result.diagnostic } : {} }); } else if (s.status === "success" && s.result && s.result.type !== "SELECT" && s.result.type !== "ASSERT") { Object.assign(entry, toMutationSummary(s.result)); } return entry; }); return { ok: batch.ok, batch: true, statementCount: batch.statementCount, statements, results, // バッチ全体の警告(仕様 §6.2)。文ごとの警告は results[].warnings に入る warnings: [] }; } // src/node/sqlDiagnostics.ts init_define_KSQL_DOCS(); function restoreSqlDiagnosticValue(value, bindings) { if (typeof value === "string") { const dmlTarget = value.match(/^(\s*target:\s*)APP(\d+) \((\d+)\)\s*$/); if (dmlTarget && dmlTarget[2] === dmlTarget[3]) { const binding = bindings.get(Number(dmlTarget[2])); if (binding) { const target = binding.source === "logical" ? `LAPP_${binding.logicalName} -> APP${binding.appId}@${binding.profile}` : `APP${binding.appId}@${binding.profile}`; return `${dmlTarget[1]}${target}`; } } let restored = value; for (const binding of bindings.values()) { const internal = `APP${binding.mappedAppId}`; const display = binding.source === "logical" ? `LAPP_${binding.logicalName}@${binding.profile}` : `APP${binding.appId}@${binding.profile}`; restored = restored.split(`${internal} (${binding.mappedAppId})`).join(display).split(internal).join(display); } return restored; } if (Array.isArray(value)) { return value.map((item) => restoreSqlDiagnosticValue(item, bindings)); } if (value !== null && typeof value === "object") { return Object.fromEntries( Object.entries(value).map(([key, item]) => [key, restoreSqlDiagnosticValue(item, bindings)]) ); } return value; } function restoreSqlContextError(err, sourceSql, context) { if (!(err instanceof Error)) return err; let message = err.message; for (const binding of context.bindings.values()) { if (binding.source === "logical") { message = message.split(`APP${binding.mappedAppId}`).join(`LAPP_${binding.logicalName}@${binding.profile}`); } } const token = err.token; if (typeof token?.pos === "number") { const segment = context.rewriteSegments.find( (candidate) => token.pos >= candidate.normalizedStart && token.pos < candidate.normalizedEnd ); if (segment) { const sourcePos = segment.sourceStart + Math.min( token.pos - segment.normalizedStart, Math.max(0, segment.sourceEnd - segment.sourceStart - 1) ); message = message.replace(/(位置 \d+、トークン:/, `\uFF08\u4F4D\u7F6E ${sourcePos}\u3001\u30C8\u30FC\u30AF\u30F3:`); const originalRef = sourceSql.slice(segment.sourceStart, segment.sourceEnd); if (segment.bindingMappedAppId !== void 0 && originalRef) { message = message.replace(/(トークン: 「)[^」]*(」)/, `$1${originalRef}$2`); } } } err.message = message; return err; } // src/import/importGateError.ts init_define_KSQL_DOCS(); var IMPORT_CAPABILITY_GATE_MARKER = "capability is disabled"; function errorMessage(error51) { if (error51 instanceof Error) return error51.message; if (typeof error51 === "string") return error51; return null; } function isImportCapabilityGateError(error51) { return errorMessage(error51)?.includes(IMPORT_CAPABILITY_GATE_MARKER) === true; } // src/node/dmlGuard.ts init_define_KSQL_DOCS(); // src/node/config.ts init_define_KSQL_DOCS(); var import_fs = require("fs"); var LOGICAL_APP_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/; var PHYSICAL_APP_KEY_RE = /^APP\d+$/i; var NUMERIC_APP_KEY_RE = /^\d+$/; var LOGICAL_SQL_KEY_RE = /^LAPP_/i; function argumentError(message) { return new Error(`ArgumentError: ${message}`); } function normalizeLogicalApps(profileName, value) { if (value === void 0) return void 0; if (value === null || typeof value !== "object" || Array.isArray(value)) { throw argumentError(`logicalApps for profile "${profileName}" must be an object.`); } const normalized = {}; const physicalIdOwners = /* @__PURE__ */ new Map(); for (const [rawName, rawAppId] of Object.entries(value)) { if (PHYSICAL_APP_KEY_RE.test(rawName) || NUMERIC_APP_KEY_RE.test(rawName) || LOGICAL_SQL_KEY_RE.test(rawName)) { throw argumentError( `logical app key "${rawName}" in profile "${profileName}" must be a logical name without APP, numeric, or LAPP_ syntax.` ); } if (!LOGICAL_APP_NAME_RE.test(rawName)) { throw argumentError( `logical app key "${rawName}" in profile "${profileName}" must match [A-Z][A-Z0-9_]{0,63}.` ); } const logicalName = rawName.toUpperCase(); if (Object.prototype.hasOwnProperty.call(normalized, logicalName)) { throw argumentError( `logical app name "${logicalName}" is duplicated after case normalization in profile "${profileName}".` ); } if (typeof rawAppId !== "number" || !Number.isSafeInteger(rawAppId) || rawAppId <= 0) { throw argumentError( `physical app ID for logical app "${logicalName}" in profile "${profileName}" must be a positive safe integer.` ); } const existingName = physicalIdOwners.get(rawAppId); if (existingName !== void 0) { throw argumentError( `logical apps "${existingName}" and "${logicalName}" in profile "${profileName}" map to the same physical app ID ${rawAppId}; physical app aliases are not supported yet.` ); } physicalIdOwners.set(rawAppId, logicalName); normalized[logicalName] = rawAppId; } return normalized; } function validateKsqlConfig(config2) { if (config2 === null || typeof config2 !== "object" || Array.isArray(config2)) { throw argumentError("config must be an object."); } if (config2.profiles === void 0) return config2; if (config2.profiles === null || typeof config2.profiles !== "object" || Array.isArray(config2.profiles)) { throw argumentError("profiles must be an object."); } for (const [profileName, profile2] of Object.entries(config2.profiles)) { if (profile2 === null || typeof profile2 !== "object" || Array.isArray(profile2)) { throw argumentError(`profile "${profileName}" must be an object.`); } if (profile2.allowPhysicalAppRefs !== void 0 && typeof profile2.allowPhysicalAppRefs !== "boolean") { throw argumentError(`allowPhysicalAppRefs for profile "${profileName}" must be boolean.`); } const logicalApps = normalizeLogicalApps(profileName, profile2.logicalApps); if (logicalApps !== void 0) profile2.logicalApps = logicalApps; if (profile2.query?.cursorMaxActive !== void 0) { const value = profile2.query.cursorMaxActive; if (!Number.isSafeInteger(value) || value < 1 || value > 5) { throw argumentError(`query.cursorMaxActive for profile "${profileName}" must be an integer from 1 to 5.`); } } if (profile2.query?.dmlMaxSubtableRows !== void 0) { const value = profile2.query.dmlMaxSubtableRows; if (!Number.isSafeInteger(value) || value <= 0) { throw argumentError(`query.dmlMaxSubtableRows for profile "${profileName}" must be a positive safe integer.`); } } } return config2; } function createAppResolutionContext(config2, defaultProfile) { const profiles = Object.fromEntries( Object.entries(config2.profiles ?? {}).map(([name, profile2]) => [ name, { logicalApps: profile2.logicalApps === void 0 ? void 0 : { ...profile2.logicalApps }, allowPhysicalAppRefs: profile2.allowPhysicalAppRefs } ]) ); const implicitDefaultProfile = {}; function requireProfile(profileName) { const profile2 = profiles[profileName]; if (!profile2 && profileName === defaultProfile) return implicitDefaultProfile; if (!profile2) throw argumentError(`profile "${profileName}" is not defined.`); return profile2; } return { resolveLogicalApp(name, profile2) { if (!LOGICAL_APP_NAME_RE.test(name)) { throw argumentError(`logical app name "${name}" must match [A-Z][A-Z0-9_]{0,63}.`); } const profileName = profile2 || defaultProfile; const logicalName = name.toUpperCase(); const appId = requireProfile(profileName).logicalApps?.[logicalName]; if (appId === void 0) { throw argumentError(`logical app LAPP_${logicalName}@${profileName} is not defined.`); } return appId; }, assertPhysicalAppAllowed(profile2) { const profileName = profile2 || defaultProfile; if (!profiles[profileName]) return; if (requireProfile(profileName).allowPhysicalAppRefs === false) { throw argumentError( `physical app references are not allowed for profile "${profileName}"; use LAPP_.` ); } } }; } function loadKsqlConfig(configPath) { const raw = (0, import_fs.readFileSync)(configPath, "utf-8"); return validateKsqlConfig(JSON.parse(raw)); } function loadOptionalKsqlConfig(configPath) { if (!(0, import_fs.existsSync)(configPath)) return {}; return loadKsqlConfig(configPath); } function envString(name) { const v = process.env[name]; return v && v.trim() ? v : null; } function envInt(name) { const v = envString(name); if (v === null) return null; const n = Number(v); if (!Number.isInteger(n) || n <= 0) return null; return n; } function envNonNegativeInt(name) { const v = envString(name); if (v === null) return null; const n = Number(v); if (!Number.isInteger(n) || n < 0) return null; return n; } function resolveRequestGateOptions(base) { return { ...base, maxConcurrent: envInt("KSQL_MAX_CONCURRENT") ?? base.maxConcurrent, // KSQL_RETRY=0(リトライ無効)は有効値のため envNonNegativeInt で読む maxRetries: envNonNegativeInt("KSQL_RETRY") ?? base.maxRetries }; } function envOnLimit(name) { const v = envString(name); if (v === "error" || v === "truncate") return v; return null; } function envAuth(name) { const v = envString(name); if (v === "token" || v === "userpass" || v === "auto") return v; return null; } function resolveTokenValue(raw) { if (raw.startsWith("env:")) { const envKey = raw.slice(4); const envVal = process.env[envKey]; if (!envVal) throw new Error(`AuthError: environment variable "${envKey}" is not set.`); return envVal; } return raw; } // src/node/runtime.ts init_define_KSQL_DOCS(); // src/api/requestGate.ts init_define_KSQL_DOCS(); var DEFAULT_MAX_CONCURRENT = 10; var DEFAULT_MAX_RETRIES = 3; var DEFAULT_BASE_DELAY_MS = 500; var DEFAULT_MAX_DELAY_MS = 8e3; var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]); function isRetryableError(err) { if (!(err instanceof Error)) return false; const status = err.message.match(/^kintone API error (\d{3}):/); if (status) return RETRYABLE_STATUSES.has(Number(status[1])); if (err.name === "AbortError" || err.name === "TimeoutError") return true; if (/fetch failed/i.test(err.message)) return true; return false; } var RequestGate = class { constructor(options = {}) { this.active = 0; this.waiters = []; this.maxConcurrent = clampInt(options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT, 1, 50); this.maxRetries = clampInt(options.maxRetries ?? DEFAULT_MAX_RETRIES, 0, 10); this.baseDelayMs = clampInt(options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS, 1, 6e4); this.maxDelayMs = Math.max( clampInt(options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS, 1, 6e5), this.baseDelayMs ); this.sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))); this.random = options.random ?? Math.random; } /** 現在の同時実行数(テスト・診断用) */ get activeCount() { return this.active; } get limit() { return this.maxConcurrent; } /** 解決済みの GET リトライ回数(テスト・診断用) */ get retries() { return this.maxRetries; } /** 解決済みのバックオフ初期値ミリ秒(テスト・診断用) */ get retryBaseDelayMs() { return this.baseDelayMs; } /** 解決済みのバックオフ上限ミリ秒(テスト・診断用) */ get retryMaxDelayMs() { return this.maxDelayMs; } /** GET 系: セマフォ + リトライ付きで実行する */ async runReadOnly(fn) { let attempt = 0; while (true) { try { return await this.withSlot(fn); } catch (err) { if (attempt >= this.maxRetries || !isRetryableError(err)) throw err; await this.sleep(this.backoffDelay(attempt)); attempt += 1; } } } /** 書き込み系: セマフォのみ(リトライしない — 二重実行防止) */ async runMutation(fn) { return this.withSlot(fn); } /** Cursor Create/Get/Delete: セマフォのみ。GETでも位置を進めるため再試行しない。 */ async runCursorStep(fn) { return this.withSlot(fn); } async withSlot(fn) { await this.acquire(); try { return await fn(); } finally { this.release(); } } async acquire() { if (this.active < this.maxConcurrent) { this.active += 1; return; } await new Promise((resolve3) => this.waiters.push(resolve3)); this.active += 1; } release() { this.active -= 1; const next = this.waiters.shift(); if (next) next(); } /** 指数バックオフ + ジッタ(attempt: 0 始まり) */ backoffDelay(attempt) { const base = Math.min(this.baseDelayMs * 2 ** attempt, this.maxDelayMs); const jitter = 1 + (this.random() - 0.5) * 0.5; return Math.round(base * jitter); } }; function withRequestGate(client, gate) { return { getRecords: (params) => gate.runReadOnly(() => client.getRecords(params)), openCursor: async (params) => { const handle = await gate.runCursorStep(() => client.openCursor(params)); return { totalCount: handle.totalCount, nextPage: () => gate.runCursorStep(() => handle.nextPage()), close: () => gate.runCursorStep(() => handle.close()) }; }, getApps: () => gate.runReadOnly(() => client.getApps()), getFields: (appId) => gate.runReadOnly(() => client.getFields(appId)), getNumberPrecision: (appId) => gate.runReadOnly(() => client.getNumberPrecision(appId)), getProcessStatuses: (appId) => gate.runReadOnly(() => client.getProcessStatuses(appId)), postRecords: (params) => gate.runMutation(() => client.postRecords(params)), putRecords: (params) => gate.runMutation(() => client.putRecords(params)), deleteRecords: (params) => gate.runMutation(() => client.deleteRecords(params)) }; } var globalGate = null; function getGlobalRequestGate(options) { if (globalGate === null) { globalGate = new RequestGate( typeof options === "number" ? { maxConcurrent: options } : options ?? {} ); } return globalGate; } function clampInt(v, min, max) { if (!Number.isFinite(v)) return min; return Math.max(min, Math.min(max, Math.trunc(v))); } // src/cli/nodeKintoneClient.ts init_define_KSQL_DOCS(); // src/core/formFieldInfo.ts init_define_KSQL_DOCS(); function flattenFormFieldProperties(properties) { return flattenFields(properties, collectLookupCopyFields(properties)); } function flattenFields(properties, lookupCopyFields, inSubtable = false, subtableCode) { const out = []; for (const field of Object.values(properties)) { const optionOrder = toOptionOrderMap(field.options); const sortKind = detectSortKind(field.type, field.format); const info = { code: field.code, label: field.label, fieldType: field.type, optionOrder, sortKind, required: field.required, minValue: normalizeConstraintValue(field.minValue), maxValue: normalizeConstraintValue(field.maxValue), minLength: normalizeConstraintValue(field.minLength), maxLength: normalizeConstraintValue(field.maxLength), defaultValue: field.defaultValue, inSubtable, ...subtableCode ? { subtableCode } : {}, writable: !lookupCopyFields.has(field.code) && !NON_WRITABLE_FIELD_TYPES3.has(field.type) }; info.semantics = resolveFieldSemantics(info); out.push(info); if (field.fields) out.push(...flattenFields(field.fields, lookupCopyFields, true, field.type === "SUBTABLE" ? field.code : subtableCode)); } return out; } var NON_WRITABLE_FIELD_TYPES3 = /* @__PURE__ */ new Set([ "CALC", "RECORD_NUMBER", "CREATOR", "CREATED_TIME", "MODIFIER", "UPDATED_TIME", "STATUS", "STATUS_ASSIGNEE", "CATEGORY", "REFERENCE_TABLE", "SUBTABLE" ]); function collectLookupCopyFields(properties) { const result = /* @__PURE__ */ new Set(); const visit = (fields) => { for (const field of Object.values(fields)) { for (const mapping of field.lookup?.fieldMappings ?? []) { if (mapping.field) result.add(mapping.field); } if (field.fields) visit(field.fields); } }; visit(properties); return result; } function normalizeConstraintValue(value) { return value == null || value === "" ? void 0 : value; } function toOptionOrderMap(options) { if (!options || typeof options !== "object") return void 0; const order = {}; let hasAny = false; for (const [label, meta3] of Object.entries(options)) { const n = Number(meta3?.index); if (!Number.isFinite(n)) continue; order[label] = n; hasAny = true; } return hasAny ? order : void 0; } function detectSortKind(fieldType, calcFormat) { if (fieldType === "NUMBER" || fieldType === "RECORD_NUMBER") return "number"; if (fieldType === "CALC") { if (calcFormat === "NUMBER" || calcFormat === "NUMBER_DIGIT") return "number"; return "string"; } return void 0; } // src/core/processStatus.ts init_define_KSQL_DOCS(); function normalizeProcessStatusStates(states) { if (states === null) return null; return Object.values(states).map((state) => { const index = Number(state.index); if (!Number.isSafeInteger(index) || index < 0) { throw new Error(`ArgumentError: invalid process status index: ${String(state.index)}`); } return { name: state.name, index }; }); } // src/api/kintoneCursor.ts init_define_KSQL_DOCS(); function isAlreadyReleasedCursorError(error51) { const shaped = error51; return shaped?.status === 404 && shaped.code === "GAIA_CN01"; } async function deleteCursorWithConfirmation(deleteCursor, sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)), isAlreadyReleased = isAlreadyReleasedCursorError) { try { await deleteCursor(); return; } catch (firstError) { if (isAlreadyReleased(firstError)) return; } await sleep(250); try { await deleteCursor(); } catch (confirmationError) { if (isAlreadyReleased(confirmationError)) return; throw confirmationError; } } async function withTimeout(promise2, timeoutMs) { let timer; const timeout2 = new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error(`CursorCleanupTimeoutError: cleanup exceeded ${timeoutMs}ms.`)), timeoutMs); timer.unref?.(); }); try { return await Promise.race([promise2, timeout2]); } finally { if (timer) clearTimeout(timer); } } function createKintoneCursorHandle(totalCount, operations) { let released = false; let closing = false; let pageTail = Promise.resolve(); let closePromise = null; const nextPage = () => { if (closing || released) return Promise.resolve({ records: [], next: false }); const result = pageTail.then(async () => { if (closing || released) return { records: [], next: false }; const page = await operations.get(); if (!page.next) { released = true; operations.onReleased?.(); } return page; }); pageTail = result.then(() => void 0, () => void 0); return result; }; const close = () => { if (released) return Promise.resolve(); if (closePromise) return closePromise; closing = true; closePromise = pageTail.then(async () => { if (released) return; try { await withTimeout( deleteCursorWithConfirmation( operations.delete, operations.sleep, operations.isAlreadyReleasedError ), operations.cleanupTimeoutMs ?? 5e3 ); released = true; operations.onReleased?.(); } catch (error51) { operations.onReleaseUnknown?.(); throw error51; } }); return closePromise; }; return { totalCount, nextPage, close }; } // src/api/cursorLeaseManager.ts init_define_KSQL_DOCS(); var DEFAULT_MAX_ACTIVE = 2; var MAX_ACTIVE = 5; var DEFAULT_WAIT_MS = 3e4; var DEFAULT_QUARANTINE_MS = 10 * 6e4 + 3e4; var CursorLeaseManager = class { constructor(host, options = {}) { this.host = host; this.active = 0; this.peak = 0; this.quarantined = 0; this.waiters = []; this.createTail = Promise.resolve(); const maxActive = options.maxActive ?? DEFAULT_MAX_ACTIVE; if (!Number.isSafeInteger(maxActive) || maxActive < 1 || maxActive > MAX_ACTIVE) { throw new Error(`ArgumentError: cursorMaxActive must be an integer from 1 to ${MAX_ACTIVE}.`); } this.maxActive = maxActive; this.waitTimeoutMs = options.waitTimeoutMs ?? DEFAULT_WAIT_MS; this.quarantineMs = options.quarantineMs ?? DEFAULT_QUARANTINE_MS; } acquire() { if (this.active < this.maxActive) { this.active += 1; this.peak = Math.max(this.peak, this.active); return Promise.resolve(this.makeLease()); } return new Promise((resolve3, reject) => { const waiter = {}; waiter.resolve = resolve3; waiter.reject = reject; waiter.timer = setTimeout(() => { const index = this.waiters.indexOf(waiter); if (index >= 0) this.waiters.splice(index, 1); reject(new CursorCapacityError(this.host, this.maxActive, this.waitTimeoutMs)); }, this.waitTimeoutMs); waiter.timer.unref?.(); this.waiters.push(waiter); }); } /** * 同一hostを共有する後続surfaceの設定を反映する。 * 縮小時は既存leaseを強制終了せず、activeが新上限を下回るまで新規取得だけを止める。 */ setMaxActive(maxActive) { this.validateMaxActive(maxActive); if (this.maxActive === maxActive) return; this.maxActive = maxActive; this.dispatchWaiters(); } async runCreate(fn) { const previous = this.createTail; let unlock; this.createTail = new Promise((resolve3) => { unlock = resolve3; }); await previous; try { return await fn(); } finally { unlock(); } } snapshot() { return { active: this.active, peak: this.peak, quarantined: this.quarantined, waiting: this.waiters.length, limit: this.maxActive }; } makeLease() { let done = false; return { release: () => { if (done) return; done = true; this.returnPermit(); }, quarantine: (durationMs = this.quarantineMs) => { if (done) return; done = true; this.quarantined += 1; const timer = setTimeout(() => { this.quarantined -= 1; this.returnPermit(); }, durationMs); timer.unref?.(); } }; } returnPermit() { this.active -= 1; this.dispatchWaiters(); } dispatchWaiters() { while (this.active < this.maxActive) { const waiter = this.waiters.shift(); if (!waiter) return; clearTimeout(waiter.timer); this.active += 1; this.peak = Math.max(this.peak, this.active); waiter.resolve(this.makeLease()); } } validateMaxActive(maxActive) { if (!Number.isSafeInteger(maxActive) || maxActive < 1 || maxActive > MAX_ACTIVE) { throw new Error(`ArgumentError: cursorMaxActive must be an integer from 1 to ${MAX_ACTIVE}.`); } } }; var managers = /* @__PURE__ */ new Map(); function getCursorLeaseManager(host, maxActive = DEFAULT_MAX_ACTIVE) { const key = host.toLowerCase(); let manager = managers.get(key); if (!manager) { manager = new CursorLeaseManager(key, { maxActive }); managers.set(key, manager); } else { manager.setMaxActive(maxActive); } return manager; } // src/core/searchAbortWarning.ts init_define_KSQL_DOCS(); var SEARCH_ABORTED_HEADER_VALUE = "Filter aborted because of too many search results"; function isSearchAbortedWarning(value) { return value?.includes(SEARCH_ABORTED_HEADER_VALUE) === true; } // src/node/kintoneMetadata.ts init_define_KSQL_DOCS(); var KINTONE_METADATA_RESOURCES = [ "app", "fields", "layout", "settings", "status", "views", "reports", "customize" ]; var KINTONE_METADATA_LANGS = ["default", "user", "ja", "en", "zh"]; var KINTONE_METADATA_MAX_RESPONSE_BYTES = 2097152; var ResponseTooLargeError = class extends Error { constructor(maxBytes = KINTONE_METADATA_MAX_RESPONSE_BYTES, responseBytes) { super(`ResponseTooLargeError: kintone metadata response exceeds ${maxBytes} bytes.`); this.maxBytes = maxBytes; this.responseBytes = responseBytes; this.name = "ResponseTooLargeError"; } }; var InvalidJsonResponseError = class extends Error { constructor(cause) { super("InvalidJsonResponseError: kintone metadata response is not valid JSON."); this.name = "InvalidJsonResponseError"; this.cause = cause; } }; var ArgumentError = class extends Error { constructor(message) { super(`ArgumentError: ${message}`); this.name = "ArgumentError"; } }; var CapabilityError = class extends Error { constructor(message) { super(`CapabilityError: ${message}`); this.name = "CapabilityError"; } }; var RESOURCE_DEFINITIONS = { app: { productionPath: "/app.json", appParameter: "id", allowsLang: false, authCapability: "token|userpass" }, fields: { productionPath: "/app/form/fields.json", previewPath: "/preview/app/form/fields.json", appParameter: "app", allowsLang: true, authCapability: "token|userpass" }, layout: { productionPath: "/app/form/layout.json", previewPath: "/preview/app/form/layout.json", appParameter: "app", allowsLang: false, authCapability: "token|userpass" }, settings: { productionPath: "/app/settings.json", previewPath: "/preview/app/settings.json", appParameter: "app", allowsLang: true, authCapability: "token|userpass" }, status: { productionPath: "/app/status.json", previewPath: "/preview/app/status.json", appParameter: "app", allowsLang: true, authCapability: "token|userpass" }, views: { productionPath: "/app/views.json", previewPath: "/preview/app/views.json", appParameter: "app", allowsLang: true, authCapability: "token|userpass" }, reports: { productionPath: "/app/reports.json", previewPath: "/preview/app/reports.json", appParameter: "app", allowsLang: true, authCapability: "token|userpass" }, customize: { productionPath: "/app/customize.json", previewPath: "/preview/app/customize.json", appParameter: "app", allowsLang: false, authCapability: "userpass-only" } }; var RESOURCE_SET = new Set(KINTONE_METADATA_RESOURCES); var LANG_SET = new Set(KINTONE_METADATA_LANGS); var API_BASE_PATH_PATTERN = /^\/k\/(?:guest\/([1-9]\d*)\/)?v1$/; function assertResolvedAppId(resolvedAppId) { if (!Number.isSafeInteger(resolvedAppId) || resolvedAppId <= 0) { throw new ArgumentError("resolved app ID must be a positive safe integer."); } } function assertApiBasePath(apiBasePath) { const match = API_BASE_PATH_PATTERN.exec(apiBasePath); if (!match) { throw new ArgumentError("apiBasePath must be /k/v1 or /k/guest//v1."); } if (match[1] !== void 0) { const guestSpaceId = Number(match[1]); if (!Number.isSafeInteger(guestSpaceId) || guestSpaceId <= 0) { throw new ArgumentError("apiBasePath guest space ID must be a positive safe integer."); } } } function validateRequest(request) { if (typeof request !== "object" || request === null || Array.isArray(request)) { throw new ArgumentError("metadata request must be an object."); } const candidate = request; const resource = candidate.resource; if (typeof resource !== "string" || !RESOURCE_SET.has(resource)) { throw new ArgumentError(`unsupported metadata resource: ${String(resource)}.`); } const typedResource = resource; const definition = RESOURCE_DEFINITIONS[typedResource]; const allowedKeys = definition.allowsLang ? /* @__PURE__ */ new Set(["resource", "preview", "lang"]) : /* @__PURE__ */ new Set(["resource", "preview"]); const unexpectedKey = Object.keys(candidate).find((key) => !allowedKeys.has(key)); if (unexpectedKey !== void 0) { throw new ArgumentError(`parameter "${unexpectedKey}" is not allowed for resource "${resource}".`); } if (candidate.preview !== void 0 && typeof candidate.preview !== "boolean") { throw new ArgumentError("preview must be a boolean when specified."); } const preview = candidate.preview === true; if (preview && definition.previewPath === void 0) { throw new ArgumentError(`preview is not supported for resource "${resource}".`); } const rawLang = candidate.lang; if (rawLang !== void 0) { if (!definition.allowsLang) { throw new ArgumentError(`lang is not allowed for resource "${resource}".`); } if (typeof rawLang !== "string" || !LANG_SET.has(rawLang)) { throw new ArgumentError(`unsupported lang: ${String(rawLang)}.`); } } return { resource: typedResource, preview, lang: rawLang, definition }; } function mapKintoneMetadataRequest(request, resolvedAppId, apiBasePath, authType) { assertResolvedAppId(resolvedAppId); assertApiBasePath(apiBasePath); if (authType !== "token" && authType !== "userpass") { throw new ArgumentError(`unsupported auth type: ${String(authType)}.`); } const { resource, preview, lang, definition } = validateRequest(request); if (definition.authCapability === "userpass-only" && authType === "token") { throw new CapabilityError(`resource "${resource}" requires userpass authentication.`); } const params = new URLSearchParams(); params.set(definition.appParameter, String(resolvedAppId)); if (lang !== void 0) params.set("lang", lang); const pathFragment = preview ? definition.previewPath : definition.productionPath; if (pathFragment === void 0) { throw new ArgumentError(`preview is not supported for resource "${resource}".`); } return { method: "GET", path: `${apiBasePath}${pathFragment}`, params, environment: preview ? "preview" : "production", resource, authCapability: definition.authCapability }; } // src/cli/nodeKintoneClient.ts var KintoneApiError = class extends Error { constructor(status, code, bodyText) { super(`kintone API error ${status}: ${bodyText}`); this.status = status; this.code = code; this.name = "KintoneApiError"; } }; function createNodeKintoneConnection(baseUrl, tokenResolver) { const normalizedBaseUrl = baseUrl.replace(/\/+$/, ""); const apiBasePath = tokenResolver.guestSpaceId && tokenResolver.guestSpaceId > 0 ? `/k/guest/${tokenResolver.guestSpaceId}/v1` : "/k/v1"; async function requestResponse(path, init, appIdForToken) { const headers = new Headers(init.headers ?? {}); if (tokenResolver.auth.type === "token") { headers.set("X-Cybozu-API-Token", tokenResolver.auth.resolveToken(appIdForToken)); } else { const credentials = `${tokenResolver.auth.username}:${tokenResolver.auth.password}`; const encoded = Buffer.from(credentials, "utf-8").toString("base64"); headers.set("X-Cybozu-Authorization", encoded); } headers.set("Accept", "application/json"); const method = String(init.method ?? "GET").toUpperCase(); if (method !== "GET" && method !== "HEAD") { headers.set("Content-Type", "application/json"); } const timeoutMs = tokenResolver.timeoutMs ?? 3e4; const url2 = `${normalizedBaseUrl}${path}`; if (tokenResolver.debug) { tokenResolver.log?.(`[debug] request ${String(init.method ?? "GET")} ${url2}`); if (tokenResolver.debugHeaders) { const authHeader = headers.get("X-Cybozu-API-Token") ? "X-Cybozu-API-Token=***" : headers.get("X-Cybozu-Authorization") ? "X-Cybozu-Authorization=***" : "Auth=(none)"; tokenResolver.log?.( `[debug] request-headers ${authHeader} Content-Type=${headers.get("Content-Type") ?? "(none)"} Accept=${headers.get("Accept") ?? "(none)"}` ); } } const controller = new AbortController(); const timeout2 = setTimeout(() => controller.abort(), timeoutMs); timeout2.unref?.(); let res; try { res = await fetch(url2, { ...init, headers, signal: controller.signal }); } finally { clearTimeout(timeout2); } if (!res.ok) { const bodyText = await res.text(); if (tokenResolver.debug) { tokenResolver.log?.(`[debug] response status=${res.status} body=${bodyText}`); } let code; try { const body = JSON.parse(bodyText); if (typeof body.code === "string") code = body.code; } catch { } throw new KintoneApiError(res.status, code, bodyText); } if (tokenResolver.debug) { tokenResolver.log?.(`[debug] response status=${res.status}`); } return { response: res, searchAborted: isSearchAbortedWarning(res.headers.get("X-Cybozu-Warning")) }; } async function requestJsonResponse(path, init, appIdForToken) { const { response, searchAborted } = await requestResponse(path, init, appIdForToken); return { body: await response.json(), searchAborted }; } async function requestJson(path, init, appIdForToken) { return (await requestJsonResponse(path, init, appIdForToken)).body; } async function requestCappedMetadataJson(path, init, appIdForToken) { const { response } = await requestResponse(path, init, appIdForToken); const contentLength = response.headers.get("Content-Length"); if (contentLength !== null && /^\d+$/.test(contentLength.trim())) { const declaredBytes = Number(contentLength); if (declaredBytes > KINTONE_METADATA_MAX_RESPONSE_BYTES) { try { await response.body?.cancel(); } catch { } throw new ResponseTooLargeError(KINTONE_METADATA_MAX_RESPONSE_BYTES, declaredBytes); } } const chunks = []; let responseBytes = 0; if (response.body !== null) { const reader = response.body.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; responseBytes += value.byteLength; if (responseBytes > KINTONE_METADATA_MAX_RESPONSE_BYTES) { try { await reader.cancel(); } catch { } throw new ResponseTooLargeError(KINTONE_METADATA_MAX_RESPONSE_BYTES, responseBytes); } chunks.push(value); } } const bytes = new Uint8Array(responseBytes); let offset = 0; for (const chunk3 of chunks) { bytes.set(chunk3, offset); offset += chunk3.byteLength; } let data; try { data = JSON.parse(new TextDecoder("utf-8").decode(bytes)); } catch (cause) { throw new InvalidJsonResponseError(cause); } if (typeof data !== "object" || data === null || Array.isArray(data)) { throw new InvalidJsonResponseError(); } return { data, responseBytes }; } function shouldRetryWithRecordNumberOrder(path, bodyText) { if (!path.includes("/v1/records.json?")) return false; if (!bodyText.includes('"code":"CB_IL02"')) return false; const queryPart = path.split("query=")[1] ?? ""; const query = decodeURIComponent(queryPart.split("&")[0] ?? ""); if (!query.includes("limit")) return false; if (!query.includes("offset")) return false; if (query.toLowerCase().includes("order by")) return false; return true; } function rewriteQueryWithRecordNumberOrder(path) { const [base, rest] = path.split("query="); if (!rest) return path; const [encodedQuery, ...tail] = rest.split("&"); const query = decodeURIComponent(encodedQuery ?? ""); const rewritten = `order by \u30EC\u30B3\u30FC\u30C9\u756A\u53F7 asc ${query}`.trim(); const nextQuery = encodeURIComponent(rewritten); return `${base}query=${nextQuery}${tail.length > 0 ? `&${tail.join("&")}` : ""}`; } const client = { async getRecords(params) { const queryPart = `query=${encodeURIComponent(params.query)}`; const appPart = `app=${encodeURIComponent(String(params.app))}`; const fieldParts = params.fields.map((f) => `fields[]=${encodeURIComponent(f)}`); const qs = [appPart, queryPart, ...fieldParts].join("&"); if (tokenResolver.debug) { tokenResolver.log?.( `[debug] getRecords app=${params.app} query="${params.query}" fields=${params.fields.length > 0 ? params.fields.join(",") : "(all)"} auth=${tokenResolver.auth.type}` ); } const path = `${apiBasePath}/records.json?${qs}`; try { const response = await requestJsonResponse( path, { method: "GET" }, params.app ); return response.searchAborted ? { ...response.body, searchAborted: true } : response.body; } catch (err) { const msg = err instanceof Error ? err.message : String(err); if (!shouldRetryWithRecordNumberOrder(path, msg)) throw err; const retryPath = rewriteQueryWithRecordNumberOrder(path); if (tokenResolver.debug) { tokenResolver.log?.("[debug] retry with fallback query order by \u30EC\u30B3\u30FC\u30C9\u756A\u53F7 asc"); } const response = await requestJsonResponse( retryPath, { method: "GET" }, params.app ); return response.searchAborted ? { ...response.body, searchAborted: true } : response.body; } }, async openCursor(params) { const manager = getCursorLeaseManager(new URL(normalizedBaseUrl).host, tokenResolver.cursorMaxActive); const lease = await manager.acquire(); let created; try { created = await manager.runCreate(() => requestJson( `${apiBasePath}/records/cursor.json`, { method: "POST", body: JSON.stringify({ app: params.app, query: params.query, size: params.size, fields: params.fields && params.fields.length > 0 ? params.fields : void 0 }) }, params.app )); } catch (error51) { if (error51 instanceof KintoneApiError) { lease.release(); throw error51; } lease.quarantine(); throw new CursorCreateOutcomeUnknownError(error51); } const cursorId = created.id; return createKintoneCursorHandle(Number(created.totalCount), { get: () => requestJson( `${apiBasePath}/records/cursor.json?id=${encodeURIComponent(cursorId)}`, { method: "GET" }, params.app ), delete: () => requestJson( `${apiBasePath}/records/cursor.json`, { method: "DELETE", body: JSON.stringify({ id: cursorId }) }, params.app ), onReleased: () => lease.release(), onReleaseUnknown: () => lease.quarantine() }); }, async postRecords(_params) { const res = await requestJson( `${apiBasePath}/records.json`, { method: "POST", body: JSON.stringify({ app: _params.app, records: _params.records }) }, _params.app ); return { ids: res.ids }; }, async putRecords(_params) { await requestJson( `${apiBasePath}/records.json`, { method: "PUT", body: JSON.stringify({ app: _params.app, records: _params.records }) }, _params.app ); }, async deleteRecords(_params) { await requestJson( `${apiBasePath}/records.json`, { method: "DELETE", body: JSON.stringify({ app: _params.app, ids: _params.ids }) }, _params.app ); }, async getApps() { const PAGE = 100; const all = []; let offset = 0; while (true) { const qs = new URLSearchParams(); qs.set("limit", String(PAGE)); qs.set("offset", String(offset)); const res = await requestJson( `${apiBasePath}/apps.json?${qs.toString()}`, { method: "GET" }, 0 ); for (const app of res.apps) { all.push({ appId: Number(app.appId), name: app.name, description: app.description }); } if (res.apps.length < PAGE) break; offset += PAGE; } return all; }, async getFields(appId) { const qs = new URLSearchParams(); qs.set("app", String(appId)); const res = await requestJson( `${apiBasePath}/app/form/fields.json?${qs.toString()}`, { method: "GET" }, appId ); return flattenFormFieldProperties(res.properties); }, async getNumberPrecision(appId) { const qs = new URLSearchParams(); qs.set("app", String(appId)); const res = await requestJson( `${apiBasePath}/app/settings.json?${qs.toString()}`, { method: "GET" }, appId ); return parseNumberPrecisionSettings(res); }, async getProcessStatuses(appId) { const qs = new URLSearchParams(); qs.set("app", String(appId)); qs.set("lang", "user"); const res = await requestJson(`${apiBasePath}/app/status.json?${qs.toString()}`, { method: "GET" }, appId); return { enable: res.enable, states: normalizeProcessStatusStates(res.states) }; } }; const metadataReader = { async getMetadata(request, resolvedAppId) { const plan = mapKintoneMetadataRequest( request, resolvedAppId, apiBasePath, tokenResolver.auth.type ); const query = plan.params.toString(); const { data, responseBytes } = await requestCappedMetadataJson( `${plan.path}${query.length > 0 ? `?${query}` : ""}`, { method: "GET" }, resolvedAppId ); return { resource: plan.resource, environment: plan.environment, path: plan.path, params: Object.fromEntries(plan.params.entries()), responseBytes, data }; } }; return { client, metadataReader }; } // src/node/appProfiles.ts init_define_KSQL_DOCS(); function parseTokenMap(raw) { const out = {}; if (!raw.trim()) return out; const pairs = raw.split(","); for (const pair of pairs) { const idx = pair.indexOf("="); if (idx <= 0) throw new Error("ArgumentError: --token-map must be APPxxx=token pairs."); const key = normalizeAppKey(pair.slice(0, idx).trim()); const value = pair.slice(idx + 1).trim(); if (!value) throw new Error(`ArgumentError: token is empty for ${key}.`); out[key] = value; } return out; } function normalizeAppKey(v) { const m1 = v.match(/^APP(\d+)$/i); if (m1) return `APP${m1[1]}`; const m2 = v.match(/^(\d+)$/); if (m2) return `APP${m2[1]}`; throw new Error(`ArgumentError: invalid app key "${v}"`); } function extractAppIds(sql) { const out = /* @__PURE__ */ new Set(); for (const t of collectAppProfileTokens(sql)) { if (t.source === "physical") out.add(t.appId); } return [...out]; } function isSqlIdentContinue(ch) { if (!ch) return false; const cp = ch.codePointAt(0); return cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp >= 48 && cp <= 57 || cp === 95 || cp === 36 || cp >= 12352 && cp <= 12543 || cp >= 13312 && cp <= 40959 || cp >= 63744 && cp <= 64255 || cp >= 65281 && cp <= 65376; } function isProfileNameChar(ch) { if (!ch) return false; const cp = ch.codePointAt(0); return cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp >= 48 && cp <= 57 || ch === "_" || ch === "-" || ch === "." || ch === "$"; } function isAsciiLogicalNameStart(ch) { return /^[A-Za-z]$/.test(ch); } function isAsciiLogicalNameContinue(ch) { return /^[A-Za-z0-9_]$/.test(ch); } function tryParseAppProfileToken(sql, start) { const prev = start > 0 ? sql[start - 1] : ""; if (isSqlIdentContinue(prev)) return null; let source; let appId; let logicalName; let referenceValueStart; let referenceValueEnd; let i; if (sql.slice(start, start + 5).toUpperCase() === "LAPP_") { source = "logical"; i = start + 5; referenceValueStart = i; if (!isAsciiLogicalNameStart(sql[i] ?? "")) return null; i++; while (i < sql.length && isAsciiLogicalNameContinue(sql[i])) i++; referenceValueEnd = i; if (referenceValueEnd - referenceValueStart > 64) return null; logicalName = sql.slice(referenceValueStart, referenceValueEnd).toUpperCase(); } else if (sql.slice(start, start + 3).toUpperCase() === "APP") { source = "physical"; i = start + 3; referenceValueStart = i; while (i < sql.length && /[0-9]/.test(sql[i])) i++; referenceValueEnd = i; if (referenceValueEnd === referenceValueStart) return null; appId = Number(sql.slice(referenceValueStart, referenceValueEnd)); } else { return null; } if (sql[i] === "$") { i++; const subStart = i; while (i < sql.length && isSqlIdentContinue(sql[i])) i++; if (i === subStart) return null; } const appEnd = i; let profile2 = null; if (sql[i] === "@") { i++; const pStart = i; while (i < sql.length && isProfileNameChar(sql[i])) i++; if (i === pStart) return null; profile2 = sql.slice(pStart, i); } const next = i < sql.length ? sql[i] : ""; if (isSqlIdentContinue(next)) return null; const common = { profile: profile2, start, referenceValueStart, referenceValueEnd, appEnd, fullEnd: i }; return source === "physical" ? { ...common, source, appId } : { ...common, source, logicalName }; } function collectAppProfileTokens(sql) { const tokens = []; let i = 0; while (i < sql.length) { const ch = sql[i]; if (ch === "'") { i++; while (i < sql.length) { if (sql[i] === "'") { i++; if (i < sql.length && sql[i] === "'") { i++; continue; } break; } i++; } continue; } if (ch === "`") { i++; while (i < sql.length && sql[i] !== "`") i++; if (i < sql.length) i++; continue; } if (ch === "-" && sql[i + 1] === "-") { i += 2; while (i < sql.length && sql[i] !== "\n") i++; continue; } if (ch === "/" && sql[i + 1] === "*") { i += 2; while (i < sql.length) { if (sql[i] === "*" && sql[i + 1] === "/") { i += 2; break; } i++; } continue; } const parsed = tryParseAppProfileToken(sql, i); if (!parsed) { i++; continue; } tokens.push(parsed); i = parsed.fullEnd; } return tokens; } function nextVirtualAppId(used) { let id = 9e8; while (used.has(id)) id++; used.add(id); return id; } function normalizeSqlAppProfiles(sql, defaultProfile = "dev", resolutionContext) { const tokens = collectAppProfileTokens(sql); const hasProfileSyntax = tokens.some((t) => t.profile !== null); const profilesByApp = /* @__PURE__ */ new Map(); const normalizedProfile = (profile2) => profile2 ?? defaultProfile; for (const t of tokens) { if (t.source !== "physical") continue; const p = normalizedProfile(t.profile); let set2 = profilesByApp.get(t.appId); if (!set2) { set2 = /* @__PURE__ */ new Set(); profilesByApp.set(t.appId, set2); } set2.add(p.toLowerCase()); } const usedAppIds = new Set( tokens.filter((t) => t.source === "physical").map((t) => t.appId) ); const resolvedLogicalApps = /* @__PURE__ */ new Map(); for (const t of tokens) { if (t.source !== "logical") continue; const pLower = normalizedProfile(t.profile).toLowerCase(); const logicalKey = `logical:${t.logicalName}@${pLower}`; if (resolvedLogicalApps.has(logicalKey)) continue; if (!resolutionContext) { throw new Error( `ArgumentError: logical app LAPP_${t.logicalName}@${pLower} requires logicalApps configuration.` ); } const resolvedAppId = resolutionContext.resolveLogicalApp(t.logicalName, pLower); resolvedLogicalApps.set(logicalKey, resolvedAppId); usedAppIds.add(resolvedAppId); } const pairToMapped = /* @__PURE__ */ new Map(); const appBindingByMappedApp = /* @__PURE__ */ new Map(); for (const [appId, pSet] of profilesByApp.entries()) { const profiles = [...pSet].sort(); if (profiles.length <= 1) continue; for (const pLower of profiles) { const mapped = nextVirtualAppId(usedAppIds); pairToMapped.set(`physical:${appId}@${pLower}`, mapped); appBindingByMappedApp.set(mapped, { source: "physical", mappedAppId: mapped, appId, profile: pLower }); } } const out = []; const rewriteSegments = []; let normalizedLength = 0; let cursor = 0; const appendSegment = (text, sourceStart, sourceEnd, bindingMappedAppId) => { if (!text && sourceStart === sourceEnd) return; const normalizedStart = normalizedLength; out.push(text); normalizedLength += text.length; rewriteSegments.push({ normalizedStart, normalizedEnd: normalizedLength, sourceStart, sourceEnd, ...bindingMappedAppId === void 0 ? {} : { bindingMappedAppId } }); }; for (const t of tokens) { const p = normalizedProfile(t.profile); const pLower = p.toLowerCase(); let binding; if (t.source === "physical") { const mapped = pairToMapped.get(`physical:${t.appId}@${pLower}`) ?? t.appId; binding = { source: "physical", mappedAppId: mapped, appId: t.appId, profile: pLower }; } else { const logicalKey = `logical:${t.logicalName}@${pLower}`; let mapped = pairToMapped.get(logicalKey); if (mapped === void 0) { mapped = nextVirtualAppId(usedAppIds); pairToMapped.set(logicalKey, mapped); } binding = { source: "logical", logicalName: t.logicalName, mappedAppId: mapped, appId: resolvedLogicalApps.get(logicalKey), profile: pLower }; } appBindingByMappedApp.set(binding.mappedAppId, binding); appendSegment(sql.slice(cursor, t.start), cursor, t.start); const subtableSuffix = sql.slice(t.referenceValueEnd, t.appEnd); const normalizedReference = t.source === "physical" ? `${sql.slice(t.start, t.referenceValueStart)}${binding.mappedAppId}${subtableSuffix}` : `APP${binding.mappedAppId}${subtableSuffix}`; appendSegment( normalizedReference, t.start, t.fullEnd, binding.mappedAppId ); cursor = t.fullEnd; } appendSegment(sql.slice(cursor), cursor, sql.length); return { normalizedSql: out.join(""), hasProfileSyntax, appBindingByMappedApp, rewriteSegments }; } function buildCacheContext(defaultProfile, appBindingByMappedApp) { if (appBindingByMappedApp.size === 0) return `default:${defaultProfile.toLowerCase()}`; const pairs = [...appBindingByMappedApp.entries()].sort((a, b) => a[0] - b[0]).map(([mappedAppId, b]) => b.source === "logical" ? `M${mappedAppId}=logical:${b.logicalName}:APP${b.appId}@${b.profile}` : `M${mappedAppId}=physical:APP${b.appId}@${b.profile}`); return `apps:${pairs.join(",")}`; } // src/node/runtime.ts var privateConfigSnapshots = /* @__PURE__ */ new WeakMap(); function cloneConfigSnapshot(config2) { return JSON.parse(JSON.stringify(config2)); } function toConfigView(config2) { const profiles = Object.fromEntries(Object.entries(config2.profiles ?? {}).map(([name, p]) => [name, { baseUrl: p.baseUrl, logicalApps: p.logicalApps === void 0 ? void 0 : Object.freeze({ ...p.logicalApps }), allowPhysicalAppRefs: p.allowPhysicalAppRefs, passwordEnv: p.passwordEnv, tokenMapSources: p.tokenMap === void 0 ? void 0 : Object.freeze(Object.fromEntries( Object.entries(p.tokenMap).map(([key, value]) => [key, String(value).startsWith("env:") ? String(value).slice(4) : "inline"]) )) }])); return Object.freeze({ defaultProfile: config2.defaultProfile, profiles: Object.freeze(profiles) }); } function resolveSqlContext(serverOptions, sql, inputProfile) { const configPath = serverOptions.configPath ?? envString("KSQL_CONFIG") ?? "./ksql.config.json"; const config2 = cloneConfigSnapshot(loadOptionalKsqlConfig(configPath)); const profileName = resolveDefaultProfile(config2, serverOptions, inputProfile); const resolutionContext = createAppResolutionContext(config2, profileName); const normalized = normalizeSqlAppProfiles(sql, profileName, resolutionContext); const bindings = normalized.appBindingByMappedApp; for (const binding of bindings.values()) { if (binding.source === "physical") resolutionContext.assertPhysicalAppAllowed(binding.profile); } const context = { normalizedSql: normalized.normalizedSql, bindings, cacheContext: buildCacheContext(profileName, bindings), profileName, rewriteSegments: Object.freeze(normalized.rewriteSegments.map((segment) => Object.freeze({ ...segment }))), hasProfileSyntax: normalized.hasProfileSyntax, configSnapshot: toConfigView(config2), logicalBindingLabels: new Map( [...bindings.values()].filter((b) => b.source === "logical").map((b) => [b.mappedAppId, `LAPP_${b.logicalName}@${b.profile}`]) ) }; Object.freeze(context); privateConfigSnapshots.set(context, config2); return context; } function resolveTokenByMappedApp(args) { const tokenByMappedApp = /* @__PURE__ */ new Map(); const tokenByPhysicalApp = /* @__PURE__ */ new Map(); const missing = []; for (const mappedAppId of args.mappedAppIds) { const binding = args.bindings.get(mappedAppId); if (!binding && args.logicalBindingLabels.has(mappedAppId)) { throw new Error(`InternalError: binding is missing for logical app ${args.logicalBindingLabels.get(mappedAppId)}.`); } const appId = binding?.appId ?? mappedAppId; const profile2 = binding?.profile ?? args.profileName; const fromMap = args.effectiveTokenMap[`APP${appId}`]; if (fromMap) { const token = resolveTokenValue(fromMap); tokenByMappedApp.set(mappedAppId, token); tokenByPhysicalApp.set(appId, token); continue; } if (binding?.source !== "logical" && args.mappedAppIds.length === 1 && args.singleToken) { tokenByMappedApp.set(mappedAppId, args.singleToken); tokenByPhysicalApp.set(appId, args.singleToken); continue; } missing.push(binding?.source === "logical" ? `LAPP_${binding.logicalName} (APP${appId})@${profile2}` : `APP${appId}@${profile2}`); } return { tokenByMappedApp, tokenByPhysicalApp, missing }; } function resolveRuntimeBinding(context, mappedAppId) { const binding = context.bindings.get(mappedAppId); if (binding) return binding; const logicalLabel = context.logicalBindingLabels.get(mappedAppId); if (logicalLabel) { throw new Error(`InternalError: binding is missing for logical app ${logicalLabel}.`); } return { appId: mappedAppId, profile: context.profileName.toLowerCase() }; } function resolveDefaultProfile(config2, serverOptions, inputProfile) { return inputProfile ?? serverOptions.profile ?? envString("KSQL_PROFILE") ?? config2.defaultProfile ?? "dev"; } function buildRuntimeConnections(input) { const profileName = input.sqlContext.profileName; const defaultProfile = input.config.profiles?.[profileName] ?? {}; const allTokenByMappedApp = /* @__PURE__ */ new Map(); const missingAppProfiles = []; const tokenMapEnv = envString("KSQL_TOKEN_MAP"); const mapFromEnv = tokenMapEnv ? parseTokenMap(tokenMapEnv) : {}; const singleToken = envString("KSQL_TOKEN"); const pendingConnections = []; for (const pName of input.usedProfiles) { const profile2 = pName === profileName ? defaultProfile : input.config.profiles?.[pName] ?? null; if (!profile2) throw new Error(`ArgumentError: profile "${pName}" is not defined.`); const baseUrl = envString("KSQL_BASE_URL") ?? profile2.baseUrl ?? ""; const guestSpaceId = envInt("KSQL_GUEST_SPACE_ID") ?? profile2.guestSpaceId ?? null; if (!baseUrl) { throw new Error(`AuthError: --base-url is required for profile "${pName}".`); } const authReq = envAuth("KSQL_AUTH") ?? profile2.auth ?? "auto"; const username = envString("KSQL_USERNAME") ?? profile2.username ?? null; const passwordFromEnvRef = profile2.passwordEnv ? envString(profile2.passwordEnv) : null; const password = envString("KSQL_PASSWORD") ?? passwordFromEnvRef ?? profile2.password ?? null; const hasUserPass = Boolean(username && password); const auth = authReq === "auto" ? hasUserPass ? "userpass" : "token" : authReq; const common = { guestSpaceId, cursorMaxActive: input.cursorMaxActive, timeoutMs: input.timeout, debug: input.debug, debugHeaders: input.debugHeaders, log: input.log }; if (auth === "userpass") { if (!username || !password) { throw new Error(`AuthError: username/password are required for profile "${pName}".`); } pendingConnections.push({ profileName: pName, baseUrl, resolver: { ...common, auth: { type: "userpass", username, password } } }); continue; } const mapFromConfig = Object.fromEntries( Object.entries(profile2.tokenMap ?? {}).map(([k, v]) => [ normalizeAppKey(k), resolveTokenValue(String(v)) ]) ); const effectiveTokenMap = { ...mapFromConfig, ...mapFromEnv }; const assignedAppIds = input.mappedAppIds.filter( (appId) => input.appProfileByApp.get(appId) === pName ); const resolvedTokens = resolveTokenByMappedApp({ mappedAppIds: assignedAppIds, profileName: pName, bindings: input.sqlContext.bindings, logicalBindingLabels: input.sqlContext.logicalBindingLabels, effectiveTokenMap, singleToken }); const tokenByApp = resolvedTokens.tokenByPhysicalApp; for (const [mappedAppId, token] of resolvedTokens.tokenByMappedApp) { allTokenByMappedApp.set(mappedAppId, token); } missingAppProfiles.push(...resolvedTokens.missing); if (assignedAppIds.length === 0 && singleToken) tokenByApp.set(0, singleToken); pendingConnections.push({ profileName: pName, baseUrl, resolver: { ...common, auth: { type: "token", resolveToken(appId) { const token = tokenByApp.get(appId) ?? tokenByApp.get(0); if (!token) { throw new Error(`AuthError: token is not resolved for APP${appId}@${pName}.`); } return token; } } } }); } if (missingAppProfiles.length > 0) { throw new Error(`AuthError: token is missing for ${missingAppProfiles.join(", ")}.`); } const connectionsByProfile = /* @__PURE__ */ new Map(); for (const pending of pendingConnections) { connectionsByProfile.set( pending.profileName, createNodeKintoneConnection(pending.baseUrl, pending.resolver) ); } return { tokenByMappedApp: allTokenByMappedApp, clientsByProfile: new Map( [...connectionsByProfile].map(([name, connection]) => [name, connection.client]) ), metadataReaderByProfile: new Map( [...connectionsByProfile].map(([name, connection]) => [name, connection.metadataReader]) ) }; } async function createKsqlRuntime(serverOptions, input) { const sqlContext = input.sqlContext ?? resolveSqlContext(serverOptions, input.sql, input.profile); const config2 = privateConfigSnapshots.get(sqlContext); if (!config2) { throw new Error("InternalError: private config snapshot is missing for resolved SQL context."); } const profileName = sqlContext.profileName; const profile2 = config2.profiles?.[profileName] ?? {}; const sql = sqlContext.normalizedSql; const maxRecords2 = input.maxRecords ?? envInt("KSQL_MAX_RECORDS") ?? profile2.query?.maxRecords ?? 500; const fetchParallel2 = input.fetchParallel ?? envInt("KSQL_FETCH_PARALLEL") ?? profile2.query?.fetchParallel ?? 3; if (!Number.isInteger(fetchParallel2) || fetchParallel2 < 1 || fetchParallel2 > 10) { throw new Error("ArgumentError: fetchParallel must be an integer between 1 and 10."); } const onLimit2 = input.onLimit ?? envOnLimit("KSQL_ON_LIMIT") ?? profile2.query?.onLimit ?? "error"; const timeout2 = input.timeout ?? envInt("KSQL_TIMEOUT") ?? profile2.query?.timeout ?? 3e4; const tempTableMaxRows2 = input.tempTableMaxRows ?? envInt("KSQL_TEMP_TABLE_MAX_ROWS") ?? profile2.query?.tempTableMaxRows; const cursorMaxActive2 = input.cursorMaxActive ?? envInt("KSQL_CURSOR_MAX_ACTIVE") ?? profile2.query?.cursorMaxActive ?? 2; if (!Number.isSafeInteger(cursorMaxActive2) || cursorMaxActive2 < 1 || cursorMaxActive2 > 5) { throw new Error("ArgumentError: cursorMaxActive must be an integer from 1 to 5."); } const appIds = extractAppIds(sql); const defaultApp = envInt("KSQL_APP") ?? profile2.app ?? null; if (appIds.length === 0 && defaultApp !== null) appIds.push(defaultApp); const appProfileByApp = /* @__PURE__ */ new Map(); for (const appId of appIds) { appProfileByApp.set( appId, sqlContext.bindings.get(appId)?.profile ?? profileName.toLowerCase() ); } const usedProfiles = /* @__PURE__ */ new Set([...appProfileByApp.values(), profileName]); const connections = buildRuntimeConnections({ sqlContext, config: config2, mappedAppIds: appIds, appProfileByApp, usedProfiles, timeout: timeout2, cursorMaxActive: cursorMaxActive2, debug: input.debug, debugHeaders: input.debugHeaders, log: input.log }); const runtimeContext = { sqlContext, tokenByMappedApp: connections.tokenByMappedApp, clientsByProfile: connections.clientsByProfile, metadataReaderByProfile: connections.metadataReaderByProfile }; const defaultClient = runtimeContext.clientsByProfile.get(profileName); if (!defaultClient) { throw new Error(`AuthError: profile client is not resolved for "${profileName}".`); } const routedClient = { getRecords: (params) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, params.app); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${params.app}.`); return routed.getRecords({ ...params, app: binding.appId }); }, openCursor: (params) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, params.app); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${params.app}.`); return routed.openCursor({ ...params, app: binding.appId }); }, postRecords: (params) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, params.app); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${params.app}.`); return routed.postRecords({ ...params, app: binding.appId }); }, putRecords: (params) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, params.app); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${params.app}.`); return routed.putRecords({ ...params, app: binding.appId }); }, deleteRecords: (params) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, params.app); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${params.app}.`); return routed.deleteRecords({ ...params, app: binding.appId }); }, getFields: (appId) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, appId); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${appId}.`); return routed.getFields(binding.appId); }, getNumberPrecision: (appId) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, appId); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${appId}.`); return routed.getNumberPrecision(binding.appId); }, getProcessStatuses: (appId) => { const binding = resolveRuntimeBinding(runtimeContext.sqlContext, appId); const routed = runtimeContext.clientsByProfile.get(binding.profile); if (!routed) throw new Error(`AuthError: profile "${binding.profile}" is not resolved for APP${appId}.`); return routed.getProcessStatuses(binding.appId); }, getApps: () => defaultClient.getApps() }; const gatedClient = withRequestGate( routedClient, getGlobalRequestGate(resolveRequestGateOptions({ maxConcurrent: profile2.query?.maxConcurrent, maxRetries: profile2.query?.retry, baseDelayMs: profile2.query?.retryBaseDelayMs, maxDelayMs: profile2.query?.retryMaxDelayMs })) ); return { sql, profileName, client: gatedClient, cacheContext: sqlContext.cacheContext, maxRecords: maxRecords2, fetchParallel: fetchParallel2, onLimit: onLimit2, timeout: timeout2, cursorMaxActive: cursorMaxActive2, tempTableMaxRows: tempTableMaxRows2 }; } var LOGICAL_METADATA_APP_REF_RE = /^LAPP_[A-Za-z][A-Za-z0-9_]{0,63}$/i; function metadataAppRefSql(app) { if (typeof app === "number") { if (!Number.isSafeInteger(app) || app <= 0) { throw new Error("ArgumentError: app must be a positive safe integer or LAPP_."); } return `SELECT * FROM APP${app}`; } if (!LOGICAL_METADATA_APP_REF_RE.test(app)) { throw new Error("ArgumentError: app must be a positive safe integer or LAPP_."); } return `SELECT * FROM ${app}`; } async function createKintoneMetadataRuntime(serverOptions, input) { const syntheticSql = metadataAppRefSql(input.app); const sqlContext = resolveSqlContext(serverOptions, syntheticSql, input.profile); const config2 = privateConfigSnapshots.get(sqlContext); if (!config2) { throw new Error("InternalError: private config snapshot is missing for resolved SQL context."); } if (input.profile !== void 0 && config2.profiles?.[sqlContext.profileName] === void 0) { throw new Error(`ArgumentError: profile "${sqlContext.profileName}" is not defined.`); } const mappedAppIds = extractAppIds(sqlContext.normalizedSql); if (mappedAppIds.length !== 1) { throw new Error("InternalError: metadata app resolution must produce exactly one app binding."); } const mappedAppId = mappedAppIds[0]; const binding = resolveRuntimeBinding(sqlContext, mappedAppId); const profile2 = binding.profile === sqlContext.profileName ? config2.profiles?.[sqlContext.profileName] ?? {} : config2.profiles?.[binding.profile]; if (!profile2) { throw new Error(`ArgumentError: profile "${binding.profile}" is not defined.`); } const timeout2 = input.timeout ?? envInt("KSQL_TIMEOUT") ?? profile2.query?.timeout ?? 3e4; const cursorMaxActive2 = input.cursorMaxActive ?? envInt("KSQL_CURSOR_MAX_ACTIVE") ?? profile2.query?.cursorMaxActive ?? 2; if (!Number.isSafeInteger(cursorMaxActive2) || cursorMaxActive2 < 1 || cursorMaxActive2 > 5) { throw new Error("ArgumentError: cursorMaxActive must be an integer from 1 to 5."); } const connections = buildRuntimeConnections({ sqlContext, config: config2, mappedAppIds, appProfileByApp: /* @__PURE__ */ new Map([[mappedAppId, binding.profile]]), usedProfiles: /* @__PURE__ */ new Set([binding.profile]), timeout: timeout2, cursorMaxActive: cursorMaxActive2, debug: input.debug, debugHeaders: input.debugHeaders, log: input.log }); const reader = connections.metadataReaderByProfile.get(binding.profile); if (!reader) { throw new Error( `AuthError: metadata reader for profile "${binding.profile}" is not resolved for APP${mappedAppId}.` ); } const gate = getGlobalRequestGate(resolveRequestGateOptions({ maxConcurrent: profile2.query?.maxConcurrent, maxRetries: profile2.query?.retry, baseDelayMs: profile2.query?.retryBaseDelayMs, maxDelayMs: profile2.query?.retryMaxDelayMs })); const metadata = await gate.runReadOnly( () => reader.getMetadata(input.request, binding.appId) ); return { sourceApp: input.app, mappedAppId, resolvedAppId: binding.appId, profileName: binding.profile, environment: metadata.environment, cacheContext: sqlContext.cacheContext, metadata }; } // src/mcp/schemas.ts init_define_KSQL_DOCS(); var profile = external_exports.string().min(1).describe("kintone connection profile name from ksql.config.json (default: the server's default profile).").optional(); var kintoneMetadataResource = external_exports.enum(KINTONE_METADATA_RESOURCES); var kintoneMetadataLang = external_exports.enum(KINTONE_METADATA_LANGS); var kintoneMetadataAppRef = external_exports.union([ external_exports.number().int().positive(), external_exports.string().regex(/^LAPP_[A-Za-z][A-Za-z0-9_]{0,63}$/i) ]).describe("Positive kintone app ID or logical app name LAPP_."); var maxRecords = external_exports.number().int().positive().describe("Maximum records fetched per SELECT (default 500).").optional(); var fetchParallel = external_exports.number().int().min(1).max(10).describe("Number of parallel kintone record-fetch requests (1-10).").optional(); var onLimit = external_exports.enum(["error", "truncate"]).describe("Behavior when maxRecords is exceeded: 'error' rejects, 'truncate' returns the first maxRecords rows (default 'error'). Local ORDER BY plans require complete input and fail instead of returning a truncated top-N; REST top-N and KORDER_NATIVE do not fetch a partial candidate set. Leading VALIDATE and DML VALIDATE ONLY always override 'truncate' to 'error'.").optional(); var tempTableMaxRows = external_exports.number().int().positive().describe("Per-temp-table cap on materialized rows for CREATE TEMP TABLE ... AS SELECT (default 10000). Overflow always errors \u2014 'truncate' never applies to temp tables, so downstream statements never see silently truncated data. Raising this increases memory use (up to 16 temp tables per batch); prefer narrowing the SELECT with WHERE.").optional(); var timeout = external_exports.number().int().positive().describe("Request timeout in milliseconds. For multi-statement batches this also acts as the total batch deadline.").optional(); var cursorMaxActive = external_exports.number().int().min(1).max(5).describe("Maximum active Cursor API handles per kintone host in this process (1-5, default 2). Later calls update the host limit; lowering it keeps existing cursors and delays new ones until active usage falls below the new limit. Create/Get are never automatically retried; capacity waits up to 30 seconds.").optional(); var savedQueryName = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/).describe("Saved query name (alphanumeric, '_' and '-', up to 64 chars)."); var savedQueryTags = external_exports.array(external_exports.string().min(1)).describe("Tags for organizing saved queries.").optional(); var importSources = external_exports.array(external_exports.object({ name: external_exports.string().min(1).describe("Source name referenced after FROM CSV."), text: external_exports.string().describe("Inline CSV text. Mutually exclusive with base64.").optional(), base64: external_exports.string().describe("Inline CSV bytes encoded as base64. Mutually exclusive with text.").optional(), encoding: external_exports.enum(["utf8", "sjis"]).describe("Optional source encoding metadata; SQL ENCODING takes precedence.").optional() }).superRefine((source, ctx) => { if (source.text === void 0 === (source.base64 === void 0)) { ctx.addIssue({ code: "custom", message: "Exactly one of text or base64 is required." }); } })).max(16).describe("IMPORT CSV/JSON named inline sources (maximum 16). Nested subtable VALIDATE ONLY/EXPLAIN is supported, but mutation is fail-closed because MCP cannot interactively display and approve parent/table delete detail. JSON drops child IDs and renumbers; cli-kintone CSV preserves matching IDs and requires REPLACE SUBTABLES. Paths are not accepted; each source is limited to 10 MiB.").optional(); var validateInputSchema = external_exports.object({ sql: external_exports.string().min(1).describe("kSQL text to validate. May contain multiple ;-separated statements (batch), temp tables (#name), and every APPLY form (UPDATE/INSERT/UPSERT/multi-value); validation never enables APPLY mutation."), profile, importSources }); var explainInputSchema = external_exports.object({ sql: external_exports.string().min(1).describe("kSQL text to explain. May contain multiple ;-separated statements (batch), temp tables (#name), and every APPLY form (UPDATE/INSERT/UPSERT/multi-value); EXPLAIN performs no record or mutation API calls."), profile, maxRecords, cursorMaxActive, importSources }); var queryInputSchema = external_exports.object({ sql: external_exports.string().min(1).describe("Read-only kSQL text. May contain multiple ;-separated statements (batch) with temp tables, e.g. CREATE TEMP TABLE #t AS SELECT ...; SELECT ... FROM #t. UPDATE/INSERT/UPSERT/multi-value APPLY VALIDATE ONLY is allowed with the fixed dmlMaxSubtableRows default 500; this schema exposes no override and never enables APPLY mutation."), profile, maxRecords, fetchParallel, onLimit, tempTableMaxRows, timeout, cursorMaxActive, importSources, continueOnError: external_exports.boolean().describe("Batch (multi-statement) only: keep executing subsequent statements after a runtime error (default false = fail-fast).").optional(), maxTotalRecords: external_exports.number().int().positive().describe("Batch (multi-statement) only: cap on total rows returned across all result sets (default: unlimited).").optional(), variables: external_exports.record(external_exports.string(), external_exports.string()).describe("Batch only: string values for variables declared with DECLARE. Keys omit @ and are case-insensitive.").optional() }); var mutateInputSchema = external_exports.object({ sql: external_exports.string().min(1).describe("DML kSQL text. May contain multiple ;-separated statements (batch) with temp tables, e.g. CREATE TEMP TABLE #t AS SELECT ...; INSERT INTO APPx (...) SELECT ... FROM #t. Every APPLY mutation form (UPDATE/INSERT/UPSERT/multi-value) is rejected by MCP v3.8.0 before runtime or records API creation."), profile, allowDml: external_exports.literal(true).describe("Must be true to acknowledge that this call writes to kintone."), confirmText: external_exports.literal("yes").describe('Must be the literal string "yes" to confirm execution.'), dmlMaxRows: external_exports.number().int().positive().describe("Per-statement cap on affected rows. The call fails before writing if any statement would exceed it; for UPSERT it counts inserts + updates. It does NOT limit source reads of INSERT/UPSERT ... SELECT: those follow the runtime maxRecords resolution (KSQL_MAX_RECORDS / profile query.maxRecords, default 500; temp tables hold at most 10000 rows by default, adjustable via tempTableMaxRows), so choose it by intended write count only."), dmlMaxSubtableRows: external_exports.number().int().positive().default(500).describe("APPLY changed-subtable-row cap (default 500). Every APPLY mutation form (UPDATE/INSERT/UPSERT/multi-value) is always rejected by MCP v3.8.0 before runtime or records API creation; allowDml and increasing dmlMaxSubtableRows do not enable it."), fetchParallel, tempTableMaxRows, timeout, cursorMaxActive, importSources, dmlTotalMaxRows: external_exports.number().int().positive().describe("Batch (multi-statement) only: cap on total affected rows across the whole batch (default: per-statement dmlMaxRows only). DML batches always run fail-fast.").optional(), variables: external_exports.record(external_exports.string(), external_exports.string()).describe("Batch only: string values for variables declared with DECLARE. Keys omit @ and are case-insensitive.").optional() }); var describeAppInputSchema = external_exports.object({ app: external_exports.number().int().positive().describe("kintone app ID to describe."), profile, maxRecords, fetchParallel, onLimit, timeout }); var showAppsInputSchema = external_exports.object({ profile, maxRecords, fetchParallel, onLimit, timeout }); var ksqlDocsInputSchema = external_exports.object({ section: external_exports.string().max(128).optional() }).strict(); var ksqlDocsInputShape = ksqlDocsInputSchema; var ksqlAppMetadataInputSchema = external_exports.discriminatedUnion("resource", [ external_exports.object({ resource: kintoneMetadataResource.extract(["app"]), app: kintoneMetadataAppRef, profile, preview: external_exports.literal(false).optional() }).strict(), external_exports.object({ resource: kintoneMetadataResource.extract(["layout", "customize"]), app: kintoneMetadataAppRef, profile, preview: external_exports.boolean().optional() }).strict(), external_exports.object({ resource: kintoneMetadataResource.extract(["fields", "settings", "status", "views", "reports"]), app: kintoneMetadataAppRef, profile, preview: external_exports.boolean().optional(), lang: kintoneMetadataLang.optional() }).strict() ]); var ksqlAppMetadataInputShape = external_exports.object({ resource: kintoneMetadataResource, app: kintoneMetadataAppRef, profile, preview: external_exports.boolean().optional(), lang: kintoneMetadataLang.optional() }).strict().superRefine((input, ctx) => { const parsed = ksqlAppMetadataInputSchema.safeParse(input); if (!parsed.success) { for (const issue2 of parsed.error.issues) { ctx.addIssue({ code: "custom", path: issue2.path, message: issue2.message }); } } }); var listQueriesInputSchema = external_exports.object({}); var saveQueryInputSchema = external_exports.object({ name: savedQueryName, title: external_exports.string().min(1).describe("Human-readable title.").optional(), description: external_exports.string().min(1).describe("What the query does and when to use it.").optional(), sql: external_exports.string().min(1).describe("kSQL text to save (single statement only)."), defaultProfile: external_exports.string().min(1).describe("Profile the saved query runs against by default."), readOnly: external_exports.boolean().describe("true for read-only queries; false marks the saved query as DML (requires mutate safety inputs at run time)."), allowProfileOverride: external_exports.boolean().describe("Allow overriding the profile at run time (default false).").optional(), tags: savedQueryTags }); var savedQueryNameInputSchema = external_exports.object({ name: savedQueryName }); var runSavedQueryInputSchema = external_exports.object({ name: savedQueryName, profile, maxRecords, fetchParallel, onLimit, timeout, allowDml: external_exports.literal(true).describe("Required for DML saved queries: must be true to acknowledge writes.").optional(), confirmText: external_exports.literal("yes").describe('Required for DML saved queries: must be the literal string "yes".').optional(), dmlMaxRows: external_exports.number().int().positive().describe("Required for DML saved queries: per-statement cap on affected rows; for UPSERT it counts inserts + updates. It does NOT limit source reads of INSERT/UPSERT ... SELECT: those follow the runtime maxRecords resolution (KSQL_MAX_RECORDS / profile query.maxRecords, default 500). Saved queries are single-statement, so temp tables do not apply here. Note: this tool's maxRecords / onLimit inputs apply to read-only saved queries only.").optional() }); var validateInputShape = validateInputSchema.shape; var explainInputShape = explainInputSchema.shape; var queryInputShape = queryInputSchema.shape; var mutateInputShape = mutateInputSchema.shape; var describeAppInputShape = describeAppInputSchema.shape; var showAppsInputShape = showAppsInputSchema.shape; var listQueriesInputShape = listQueriesInputSchema.shape; var saveQueryInputShape = saveQueryInputSchema.shape; var savedQueryNameInputShape = savedQueryNameInputSchema.shape; var runSavedQueryInputShape = runSavedQueryInputSchema.shape; // src/mcp/savedQueries.ts init_define_KSQL_DOCS(); var import_promises = require("node:fs/promises"); var import_node_path2 = require("node:path"); var SAVED_QUERY_CATALOG_VERSION = 1; var DEFAULT_SAVED_QUERY_CATALOG_PATH = ".ksql/queries.json"; var SAVED_QUERY_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/; function isPlainObject3(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function optionalString(value) { return typeof value === "string" && value.length > 0 ? value : void 0; } function normalizeTags(tags) { if (!tags) return void 0; const normalized = [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))]; return normalized.length > 0 ? normalized : void 0; } function resolvePath(path, baseDir) { return (0, import_node_path2.isAbsolute)(path) ? path : (0, import_node_path2.resolve)(baseDir, path); } function resolveSavedQueryCatalogPath(options = {}) { const cwd = options.cwd ?? process.cwd(); const envPath = envString("KSQL_SAVED_QUERIES"); if (options.inputPath) return resolvePath(options.inputPath, cwd); if (envPath) return resolvePath(envPath, cwd); const configBaseDir = options.configPath ? (0, import_node_path2.dirname)((0, import_node_path2.resolve)(cwd, options.configPath)) : cwd; const configured = options.configSavedQueriesPath ?? DEFAULT_SAVED_QUERY_CATALOG_PATH; return resolvePath(configured, configBaseDir); } function emptySavedQueryCatalog() { return { version: SAVED_QUERY_CATALOG_VERSION, queries: [] }; } function validateSavedQueryName(name) { if (!SAVED_QUERY_NAME_PATTERN.test(name)) { throw new Error( "ArgumentError: saved query name must start with an ASCII letter or digit and contain only letters, digits, underscores, or hyphens, up to 64 characters." ); } } function assertSavedQuerySafety(input, safety) { if (input.readOnly && safety.isDml) { throw new Error(`ArgumentError: readOnly saved query cannot contain ${safety.statementType}.`); } if (!input.readOnly && !safety.isDml) { throw new Error("ArgumentError: readOnly: false is only allowed for DML saved queries."); } } function assertProfileOverrideAllowed(query, requestedProfile) { if (!requestedProfile || requestedProfile === query.defaultProfile) return; if (!query.allowProfileOverride) { throw new Error(`ArgumentError: saved query ${query.name} does not allow profile override.`); } } function parseSavedQueryCatalog(raw) { let parsed; try { parsed = JSON.parse(raw); } catch (err) { throw new Error(`ArgumentError: saved query catalog JSON is invalid: ${err instanceof Error ? err.message : String(err)}`); } if (!isPlainObject3(parsed) || parsed.version !== SAVED_QUERY_CATALOG_VERSION || !Array.isArray(parsed.queries)) { throw new Error("ArgumentError: saved query catalog must be an object with version: 1 and queries array."); } const queries = parsed.queries.map((item) => { if (!isPlainObject3(item)) { throw new Error("ArgumentError: saved query catalog contains a non-object query."); } const name = item.name; const sql = item.sql; const defaultProfile = item.defaultProfile; const readOnly = item.readOnly; const createdAt = item.createdAt; const updatedAt = item.updatedAt; if (typeof name !== "string" || typeof sql !== "string" || typeof defaultProfile !== "string") { throw new Error("ArgumentError: saved query catalog query requires name, sql, and defaultProfile strings."); } if (typeof readOnly !== "boolean" || typeof createdAt !== "string" || typeof updatedAt !== "string") { throw new Error("ArgumentError: saved query catalog query requires readOnly boolean and timestamp strings."); } validateSavedQueryName(name); const tags = Array.isArray(item.tags) ? normalizeTags(item.tags.filter((tag) => typeof tag === "string")) : void 0; return { name, title: optionalString(item.title), description: optionalString(item.description), sql, defaultProfile, readOnly, allowProfileOverride: item.allowProfileOverride === true ? true : void 0, createdAt, updatedAt, tags }; }); const names = /* @__PURE__ */ new Set(); for (const query of queries) { if (names.has(query.name)) { throw new Error(`ArgumentError: duplicate saved query name ${query.name}.`); } names.add(query.name); } return { version: SAVED_QUERY_CATALOG_VERSION, queries }; } async function loadSavedQueryCatalog(filePath) { try { return parseSavedQueryCatalog(await (0, import_promises.readFile)(filePath, "utf8")); } catch (err) { const code = err.code; if (code === "ENOENT") { return emptySavedQueryCatalog(); } throw err; } } async function saveSavedQueryCatalog(filePath, catalog) { await (0, import_promises.mkdir)((0, import_node_path2.dirname)(filePath), { recursive: true }); const sorted = { version: SAVED_QUERY_CATALOG_VERSION, queries: [...catalog.queries].sort((a, b) => a.name.localeCompare(b.name)) }; await (0, import_promises.writeFile)(filePath, `${JSON.stringify(sorted, null, 2)} `, "utf8"); } function upsertSavedQuery(catalog, input, now = /* @__PURE__ */ new Date()) { validateSavedQueryName(input.name); if (!input.sql.trim()) { throw new Error("ArgumentError: saved query sql must not be empty."); } if (!input.defaultProfile.trim()) { throw new Error("ArgumentError: saved query defaultProfile must not be empty."); } const nowIso = now.toISOString(); const existing = catalog.queries.find((query2) => query2.name === input.name); const query = { name: input.name, title: optionalString(input.title), description: optionalString(input.description), sql: input.sql, defaultProfile: input.defaultProfile, readOnly: input.readOnly, allowProfileOverride: input.allowProfileOverride === true ? true : void 0, createdAt: existing?.createdAt ?? nowIso, updatedAt: nowIso, tags: normalizeTags(input.tags) }; const queries = existing ? catalog.queries.map((item) => item.name === input.name ? query : item) : [...catalog.queries, query]; return { catalog: { version: SAVED_QUERY_CATALOG_VERSION, queries }, query, created: !existing }; } function getSavedQuery(catalog, name) { const query = catalog.queries.find((item) => item.name === name); if (!query) { throw new Error(`ArgumentError: saved query ${name} was not found.`); } return query; } function deleteSavedQuery(catalog, name) { const queries = catalog.queries.filter((query) => query.name !== name); return { catalog: { version: SAVED_QUERY_CATALOG_VERSION, queries }, deleted: queries.length !== catalog.queries.length }; } // src/mcp/tools.ts function requireSingleStatement(validation, toolName) { if (validation.batch) { throw new Error( `ArgumentError: batch SQL (multiple statements) is not supported by ${toolName} yet.` ); } return validation; } var DEFAULT_MAX_RECORDS = 500; var DEFAULT_ON_LIMIT = "error"; var MCP_IMPORT_SOURCE_REQUIRED_MESSAGE = "IMPORT \u306B\u306F importSources\uFF08inline CSV/JSON\uFF09\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002"; function importCapability(input) { const sources = input.importSources; if (!sources || sources.length === 0) return {}; const byName = /* @__PURE__ */ new Map(); for (const source of sources) { if (byName.has(source.name)) throw new Error(`ArgumentError: duplicate import source name: ${source.name}`); let bytes; if (source.text !== void 0 && source.base64 === void 0) { bytes = new TextEncoder().encode(source.text); } else if (source.base64 !== void 0 && source.text === void 0) { const normalized = source.base64.replace(/\s/g, ""); if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(normalized)) { throw new Error(`ArgumentError: invalid base64 for import source: ${source.name}`); } bytes = new Uint8Array(Buffer.from(normalized, "base64")); } else { throw new Error(`ArgumentError: import source ${source.name} requires exactly one of text or base64.`); } byName.set(source.name, { bytes, encoding: source.encoding }); } return { enableImport: true, importSource: (name) => { const source = byName.get(name); return source ? { load: async () => source } : void 0; } }; } function toMcpImportError(error51, importEnabled) { if (importEnabled || !isImportCapabilityGateError(error51)) return error51; if (error51 instanceof Error) { error51.message = MCP_IMPORT_SOURCE_REQUIRED_MESSAGE; return error51; } return MCP_IMPORT_SOURCE_REQUIRED_MESSAGE; } function noOpClient() { const fail3 = async () => { throw new Error("No-op client should not be called."); }; return { getRecords: fail3, openCursor: fail3, postRecords: fail3, putRecords: fail3, deleteRecords: fail3, getApps: fail3, getFields: fail3, async getProcessStatuses() { return { enable: false, states: [] }; }, async getNumberPrecision() { return { digits: 30, decimalPlaces: 10, roundingMode: "HALF_EVEN" }; } }; } function getServerConfigPath(serverOptions) { return serverOptions.configPath ?? envString("KSQL_CONFIG") ?? "./ksql.config.json"; } function getSavedQueryCatalogPath(serverOptions) { const configPath = getServerConfigPath(serverOptions); const config2 = loadOptionalKsqlConfig(configPath); return resolveSavedQueryCatalogPath({ configPath, configSavedQueriesPath: config2.mcp?.savedQueries?.path }); } function normalizeSqlForTool(serverOptions, sql, inputProfile) { const sqlContext = resolveSqlContext(serverOptions, sql, inputProfile); return { profileName: sqlContext.profileName, normalizedSql: sqlContext.normalizedSql, hasProfileSyntax: sqlContext.hasProfileSyntax, appBindingByMappedApp: sqlContext.bindings, cacheContext: sqlContext.cacheContext, sqlContext, sourceSql: sql }; } function toValidationBinding(mappedAppId, binding) { return binding.source === "logical" ? { source: binding.source, logicalName: binding.logicalName, mappedAppId, appId: binding.appId, profile: binding.profile } : { source: binding.source, mappedAppId, appId: binding.appId, profile: binding.profile }; } function toExplainBindings(bindings) { return [...bindings.values()].map((binding) => binding.source === "logical" ? { source: binding.source, logicalName: binding.logicalName, appId: binding.appId, profile: binding.profile } : { source: binding.source, appId: binding.appId, profile: binding.profile }); } function explainSql(sql) { return /^\s*EXPLAIN\b/i.test(sql) ? sql : `EXPLAIN ${sql}`; } function toSelectPayload(result) { return { ok: true, type: result.type, columns: result.columns, rows: result.rows, rowCount: result.rowCount, warnings: result.warnings ?? [], ...result.validateStats ? { validateStats: result.validateStats } : {} }; } function toAssertPayload(result) { return { ok: true, type: result.type, condition: result.condition }; } function toDmlValidationPayload(result) { return { ok: true, type: result.type, operation: result.operation, validatedRows: result.validatedRows, validRows: result.validRows, invalidRows: result.invalidRows, errorCount: result.errorCount, columns: result.columns, errors: result.errors, ...result.errTable ? { errTable: result.errTable } : {}, ...result.importDetail ? { importDetail: result.importDetail } : {}, ...result.apply ? { apply: result.apply } : {}, ...result.guards ? { guards: result.guards } : {}, ...result.deletedRows ? { deletedRows: result.deletedRows } : {} }; } function statementHasApplyBlocks(statement) { const target = statement.type === "EXPLAIN" ? statement.query : statement; if (target.type !== "UPDATE" && target.type !== "INSERT" && target.type !== "UPSERT") return false; const candidate = target; return ["applyBlocks", "onInsertApplyBlocks", "onUpdateApplyBlocks"].some((key) => Array.isArray(candidate[key]) && candidate[key].length > 0); } function toMutationPayload(result) { if (result.type === "INSERT") { return { ok: true, type: result.type, insertedCount: result.insertedCount, createdIds: result.createdIds, ...result.affectedRows !== void 0 ? { affectedRows: result.affectedRows } : {}, ...result.skippedRows !== void 0 ? { skippedRows: result.skippedRows } : {}, ...result.rejectLimit !== void 0 ? { rejectLimit: result.rejectLimit } : {}, ...result.errTable !== void 0 ? { errTable: result.errTable } : {} }; } if (result.type === "UPDATE") { return { ok: true, type: result.type, updatedCount: result.updatedCount, ...result.affectedRows !== void 0 ? { affectedRows: result.affectedRows } : {}, ...result.skippedRows !== void 0 ? { skippedRows: result.skippedRows } : {}, ...result.rejectLimit !== void 0 ? { rejectLimit: result.rejectLimit } : {}, ...result.errTable !== void 0 ? { errTable: result.errTable } : {} }; } if (result.type === "DELETE") { return { ok: true, type: result.type, deletedCount: result.deletedCount }; } if (result.type === "UPSERT") { return { ok: true, type: result.type, insertedCount: result.insertedCount, updatedCount: result.updatedCount, ...result.affectedRows !== void 0 ? { affectedRows: result.affectedRows } : {}, ...result.skippedRows !== void 0 ? { skippedRows: result.skippedRows } : {}, ...result.rejectLimit !== void 0 ? { rejectLimit: result.rejectLimit } : {}, ...result.errTable !== void 0 ? { errTable: result.errTable } : {} }; } return { ok: true, type: result.type, reorderedParentCount: result.reorderedParentCount }; } function toErrorPayload(err) { const message = err instanceof Error ? err.message : String(err); const codeMatch = message.match(/^([A-Za-z]+Error):/); const errorName = err instanceof Error && err.name !== "Error" ? err.name : null; return { ok: false, error: { code: errorName ?? codeMatch?.[1] ?? "Error", message } }; } function sanitizeMetadataError(err) { if (err instanceof Error && err.name === "KintoneApiError") { const apiError = err; if (Number.isInteger(apiError.status)) { const safe = new Error( `kintone API error ${String(apiError.status)}` + (typeof apiError.code === "string" && apiError.code.length > 0 ? ` (${apiError.code})` : "") + "." ); safe.name = "KintoneApiError"; return safe; } } return err; } function requireDmlApproval(input, toolName, suffix = "") { const context = suffix ? ` ${suffix}` : ""; if (input.allowDml !== true) { throw new Error(`ArgumentError: allowDml: true is required by ${toolName}${context}.`); } if (input.confirmText !== "yes") { throw new Error(`ArgumentError: confirmText: "yes" is required by ${toolName}${context}.`); } if (!Number.isInteger(input.dmlMaxRows) || Number(input.dmlMaxRows) <= 0) { throw new Error(`ArgumentError: dmlMaxRows must be a positive integer for ${toolName}${context}.`); } return Number(input.dmlMaxRows); } function containsSelectBasedDml(statements) { return statements.some( (s) => s.statementType === "INSERT_SELECT" || s.statementType === "UPSERT_SELECT" || s.isUpdateFrom === true || s.isOnErrorSkip === true ); } function resolveMutateRuntimeMaxRecords(statements, dmlMaxRows) { return containsSelectBasedDml(statements) ? void 0 : dmlMaxRows + 1; } var READ_LIMIT_MESSAGE_FRAGMENT = "\u53D6\u5F97\u4EF6\u6570\u304C\u4E0A\u9650"; var SELECT_BASED_DML_READ_LIMIT_HINT = "SELECT-based DML\uFF08UPDATE \u2026 FROM \u3092\u542B\u3080\uFF09\u306E\u30BD\u30FC\u30B9\u8AAD\u307F\u53D6\u308A\u4E0A\u9650\u306F dmlMaxRows \u3067\u306F\u306A\u304F maxRecords \u89E3\u6C7A\u5024(KSQL_MAX_RECORDS / profile \u306E query.maxRecords\u3001\u65E2\u5B9A 500)\u3067\u5236\u5FA1\u3055\u308C\u307E\u3059\u3002dmlMaxRows \u306F\u5F71\u97FF\u884C\u6570\u30AC\u30FC\u30C9\u3067\u3059\u3002"; function appendSelectBasedDmlReadLimitHint(err) { if (err instanceof Error && err.message.includes(READ_LIMIT_MESSAGE_FRAGMENT)) { const hinted = new Error(`${err.message} ${SELECT_BASED_DML_READ_LIMIT_HINT}`); hinted.name = err.name; return hinted; } return err; } function toToolResult(payload, isError = false) { return { content: [ { type: "text", text: JSON.stringify(payload, null, 2) } ], structuredContent: payload, isError }; } async function runSafely(fn) { try { return toToolResult(await fn()); } catch (err) { return toToolResult(toErrorPayload(err), true); } } function createKsqlMcpTools(serverOptions, deps = {}) { const createRuntime = deps.createRuntime ?? createKsqlRuntime; const createMetadataRuntime = deps.createMetadataRuntime ?? createKintoneMetadataRuntime; const executeSql = deps.executeSql ?? execute; const executeBatchSql = deps.executeBatchSql ?? executeBatch; const validationContexts = /* @__PURE__ */ new WeakMap(); const applyMutationValidations = /* @__PURE__ */ new WeakSet(); async function validate(input) { const normalized = normalizeSqlForTool(serverOptions, input.sql, input.profile); const importOptions = importCapability(input); let analysis; let statements; try { statements = parseSqlStatements(normalized.normalizedSql, { import: importOptions.enableImport }); analysis = analyzeBatch(statements); } catch (err) { const restored = restoreSqlContextError(err, normalized.sourceSql, normalized.sqlContext); throw toMcpImportError(restored, importOptions.enableImport === true); } const appBindings = [...normalized.appBindingByMappedApp.entries()].map(([mappedAppId, binding]) => toValidationBinding(mappedAppId, binding)); const hasApplyMutation = statements.some( (statement, index) => analysis.statements[index]?.isDml === true && statementHasApplyBlocks(statement) ); const statementValidations = analysis.statements.map((s2) => ({ index: s2.index, statementType: s2.statementType, isDml: s2.isDml, isReadOnly: s2.isReadOnly, hasWhere: s2.hasWhere, insertValuesCount: s2.insertValuesCount, appIds: s2.appIds, tempTablesCreated: s2.tempTablesCreated, tempTablesReferenced: s2.tempTablesReferenced, tempTablesDropped: s2.tempTablesDropped, tempOnlySource: s2.tempOnlySource, targetAppId: s2.targetAppId, isUpdateFrom: s2.isUpdateFrom, isValidationOnly: s2.isValidationOnly, isOnErrorSkip: s2.isOnErrorSkip, requiresCompleteInput: s2.requiresCompleteInput })); const common = { ok: true, statementCount: analysis.statementCount, isReadOnlyBatch: analysis.isReadOnlyBatch, containsDml: analysis.containsDml, containsValidationOnly: analysis.containsValidationOnly, requiresCompleteInput: analysis.requiresCompleteInput, tempTables: analysis.tempTables, canRunWithQueryTool: analysis.isReadOnlyBatch, requiresMutationTool: analysis.containsDml, statements: statementValidations, normalizedSql: normalized.normalizedSql, hasProfileSyntax: normalized.hasProfileSyntax, cacheContext: normalized.cacheContext, appBindings }; if (analysis.statementCount > 1) { const result2 = { ...common, batch: true }; validationContexts.set(result2, normalized.sqlContext); if (hasApplyMutation) applyMutationValidations.add(result2); return result2; } const s = statementValidations[0]; const result = { ...common, batch: false, statementType: s.statementType, isDml: s.isDml, isReadOnly: s.isReadOnly, hasWhere: s.hasWhere, insertValuesCount: s.insertValuesCount, appIds: s.appIds }; validationContexts.set(result, normalized.sqlContext); if (hasApplyMutation) applyMutationValidations.add(result); return result; } async function explain(input) { const normalized = normalizeSqlForTool(serverOptions, input.sql, input.profile); const importOptions = importCapability(input); const appBindings = toExplainBindings(normalized.appBindingByMappedApp); let statements; try { statements = parseSqlStatements(normalized.normalizedSql, { import: importOptions.enableImport }); } catch (err) { const restored = restoreSqlContextError(err, normalized.sourceSql, normalized.sqlContext); throw toMcpImportError(restored, importOptions.enableImport === true); } const needsAppMetadata = normalized.appBindingByMappedApp.size > 0 && statements.some(explainNeedsAppMetadata); const runtime = needsAppMetadata ? await createRuntime(serverOptions, { sql: input.sql, sqlContext: normalized.sqlContext, profile: input.profile, maxRecords: input.maxRecords, cursorMaxActive: input.cursorMaxActive }) : null; const explainClient = runtime?.client ?? noOpClient(); const explainCacheContext = runtime?.cacheContext ?? normalized.cacheContext; const explainSourceSql = runtime?.sql ?? normalized.normalizedSql; if (statements.length > 1) { const plans = await buildBatchExplainPlans( explainSourceSql, explainClient, void 0, explainCacheContext, runtime?.maxRecords ?? input.maxRecords, runtime?.cursorMaxActive ?? input.cursorMaxActive ?? 2, importOptions.enableImport ); return { ok: true, batch: true, statementCount: plans.statementCount, statements: restoreSqlDiagnosticValue(plans.statements, normalized.appBindingByMappedApp), appBindings }; } const result = await executeSql(explainSql(explainSourceSql), explainClient, { cacheContext: explainCacheContext, maxRecords: runtime?.maxRecords ?? input.maxRecords, cursorMaxActive: runtime?.cursorMaxActive ?? input.cursorMaxActive ?? 2, ...importOptions }); if (result.type !== "SELECT") { throw new Error(`ArgumentError: EXPLAIN returned unexpected result type ${result.type}.`); } return restoreSqlDiagnosticValue( { ...toSelectPayload(result), appBindings }, normalized.appBindingByMappedApp ); } async function query(input, validated) { const validation = validated ?? await validate(input); const importOptions = importCapability(input); if (!validation.batch && input.variables && Object.keys(input.variables).length > 0) { throw new Error("ArgumentError: variables require a batch containing DECLARE."); } if (validation.batch) { if (validation.containsDml) { throw new Error("ArgumentError: batch contains DML statements. Use ksql_mutate."); } const runtime2 = await createRuntime(serverOptions, { sql: input.sql, sqlContext: validationContexts.get(validation), profile: input.profile, maxRecords: input.maxRecords, fetchParallel: input.fetchParallel, onLimit: validation.containsValidationOnly || validation.statements.some((s) => s.statementType === "VALIDATE") ? "error" : input.onLimit, timeout: input.timeout, tempTableMaxRows: input.tempTableMaxRows, cursorMaxActive: input.cursorMaxActive }); const batchResult = await executeBatchSql(runtime2.sql, runtime2.client, { maxRecords: runtime2.maxRecords, fetchParallel: runtime2.fetchParallel, onLimitReached: runtime2.onLimit, cacheContext: runtime2.cacheContext, continueOnError: input.continueOnError, // 一時テーブル実体化上限(未指定 = エンジン既定 TEMP_TABLE_MAX_ROWS)。 // 実体化は onLimit 設定によらず常に error(src/execute.ts の実体化経路で固定) tempTableMaxRows: runtime2.tempTableMaxRows, // バッチでは timeout を合計タイムアウトとして扱う(仕様 §5.7)。 // runtime.timeout は env / profile / 既定 30000ms を解決済みの値で、 // HTTP クライアント側の per-request タイムアウトと同値になる timeoutMs: runtime2.timeout, cursorMaxActive: runtime2.cursorMaxActive ?? input.cursorMaxActive ?? 2, variables: input.variables, ...importOptions }); return { ...buildBatchEnvelope(batchResult, { maxTotalRecords: input.maxTotalRecords }) }; } if (!validation.isReadOnly) { throw new Error(`ArgumentError: ${validation.statementType} is not allowed by ksql_query. Use ksql_mutate.`); } const stmt = parseSqlStatement(validation.normalizedSql, { import: importOptions.enableImport }); const noAppApiNeeded = isNoFromSelectStatement(stmt); if (noAppApiNeeded) { const result2 = await executeSql(validation.normalizedSql, noOpClient(), { maxRecords: input.maxRecords ?? DEFAULT_MAX_RECORDS, onLimitReached: input.onLimit ?? DEFAULT_ON_LIMIT, cacheContext: validation.cacheContext, ...importOptions }); if (result2.type === "ASSERT") return toAssertPayload(result2); if (result2.type === "VALIDATION") return toDmlValidationPayload(result2); if (result2.type !== "SELECT") { throw new Error(`ArgumentError: read-only query returned unexpected result type ${result2.type}.`); } return toSelectPayload(result2); } const runtime = await createRuntime(serverOptions, { sql: input.sql, sqlContext: validationContexts.get(validation), profile: input.profile, maxRecords: input.maxRecords, fetchParallel: input.fetchParallel, onLimit: validation.containsValidationOnly || validation.statements.some((s) => s.statementType === "VALIDATE") ? "error" : input.onLimit, timeout: input.timeout, cursorMaxActive: input.cursorMaxActive }); const result = await executeSql(runtime.sql, runtime.client, { maxRecords: runtime.maxRecords, fetchParallel: runtime.fetchParallel, onLimitReached: runtime.onLimit, cacheContext: runtime.cacheContext, cursorMaxActive: runtime.cursorMaxActive ?? input.cursorMaxActive ?? 2, ...importOptions }); if (result.type === "ASSERT") return toAssertPayload(result); if (result.type === "VALIDATION") return toDmlValidationPayload(result); if (result.type !== "SELECT") { throw new Error(`ArgumentError: read-only query returned unexpected result type ${result.type}.`); } return toSelectPayload(result); } async function mutateBatch(input, validation, dmlMaxRows) { const importOptions = importCapability(input); if (!validation.containsDml) { throw new Error("ArgumentError: batch contains no DML statements. Use ksql_query."); } let staticInsertTotal = 0; for (const s of validation.statements) { if (!s.isDml) continue; const at = ` (statement ${s.index})`; if ((s.statementType === "UPDATE" || s.statementType === "DELETE") && !s.hasWhere) { throw new Error(`ArgumentError: ${s.statementType} without WHERE is blocked by ksql_mutate.${at}`); } if (!s.isOnErrorSkip && s.insertValuesCount !== null && s.insertValuesCount > dmlMaxRows) { throw new Error( `ArgumentError: INSERT rows (${s.insertValuesCount}) exceed dmlMaxRows (${dmlMaxRows}).${at}` ); } if (!s.isOnErrorSkip) staticInsertTotal += s.insertValuesCount ?? 0; } const dmlTotalMaxRows = input.dmlTotalMaxRows; if (dmlTotalMaxRows !== void 0 && staticInsertTotal > dmlTotalMaxRows) { throw new Error( `ArgumentError: batch INSERT rows (${staticInsertTotal}) exceed dmlTotalMaxRows (${dmlTotalMaxRows}).` ); } const selectBasedDml = containsSelectBasedDml(validation.statements); const runtime = await createRuntime(serverOptions, { sql: input.sql, sqlContext: validationContexts.get(validation), profile: input.profile, // SELECT-based DML を含む場合は dmlMaxRows で読み取りを絞らない(案A。 // resolveMutateRuntimeMaxRecords の doc コメント参照) maxRecords: resolveMutateRuntimeMaxRecords(validation.statements, dmlMaxRows), fetchParallel: input.fetchParallel, onLimit: DEFAULT_ON_LIMIT, timeout: input.timeout, tempTableMaxRows: input.tempTableMaxRows, cursorMaxActive: input.cursorMaxActive }); let totalAffected = staticInsertTotal; const batchResult = await executeBatchSql(runtime.sql, runtime.client, { maxRecords: runtime.maxRecords, fetchParallel: runtime.fetchParallel, onLimitReached: runtime.onLimit, cacheContext: runtime.cacheContext, // 一時テーブル実体化上限(未指定 = エンジン既定 TEMP_TABLE_MAX_ROWS) tempTableMaxRows: runtime.tempTableMaxRows, // 合計タイムアウト(解決済みの runtime.timeout。per-request と同値) timeoutMs: runtime.timeout, cursorMaxActive: runtime.cursorMaxActive ?? input.cursorMaxActive ?? 2, variables: input.variables, ...importOptions, confirm: async (count, operation) => { if (count > dmlMaxRows) { throw new Error(`ArgumentError: ${operation} affected rows (${count}) exceed dmlMaxRows (${dmlMaxRows}).`); } totalAffected += count; if (dmlTotalMaxRows !== void 0 && totalAffected > dmlTotalMaxRows) { throw new Error( `ArgumentError: batch affected rows (${totalAffected}) exceed dmlTotalMaxRows (${dmlTotalMaxRows}).` ); } return true; } }); const payload = buildBatchEnvelope(batchResult); if (selectBasedDml) { for (const entry of payload.statements) { const statement = validation.statements.find((s) => s.index === entry.index); if (entry.type !== "INSERT_SELECT" && entry.type !== "UPSERT_SELECT" && statement?.isUpdateFrom !== true) continue; const error51 = entry.error; if (typeof error51?.message !== "string") continue; if (!error51.message.includes(READ_LIMIT_MESSAGE_FRAGMENT)) continue; entry.error = { ...error51, message: `${error51.message} ${SELECT_BASED_DML_READ_LIMIT_HINT}` }; } } return { ...payload }; } async function mutate(input, validated) { const dmlMaxRows = requireDmlApproval(input, "ksql_mutate"); const importOptions = importCapability(input); const validation = validated ?? await validate(input); if (applyMutationValidations.has(validation)) { throw new Error("UnsupportedError: APPLY mutation is disabled in MCP v3.8.0"); } if (!validation.batch && input.variables && Object.keys(input.variables).length > 0) { throw new Error("ArgumentError: variables require a batch containing DECLARE."); } if (validation.batch) { return mutateBatch(input, validation, dmlMaxRows); } if (!validation.isDml) { throw new Error(`ArgumentError: ${validation.statementType} is not allowed by ksql_mutate. Use ksql_query.`); } if ((validation.statementType === "UPDATE" || validation.statementType === "DELETE") && !validation.hasWhere) { throw new Error(`ArgumentError: ${validation.statementType} without WHERE is blocked by ksql_mutate.`); } if (validation.insertValuesCount !== null && validation.insertValuesCount > dmlMaxRows) { throw new Error(`ArgumentError: INSERT rows (${validation.insertValuesCount}) exceed dmlMaxRows (${dmlMaxRows}).`); } const selectBasedDml = containsSelectBasedDml(validation.statements); const runtime = await createRuntime(serverOptions, { sql: input.sql, sqlContext: validationContexts.get(validation), profile: input.profile, // SELECT-based DML は dmlMaxRows で読み取りを絞らない(案A。 // resolveMutateRuntimeMaxRecords の doc コメント参照) maxRecords: resolveMutateRuntimeMaxRecords(validation.statements, dmlMaxRows), fetchParallel: input.fetchParallel, onLimit: DEFAULT_ON_LIMIT, timeout: input.timeout, cursorMaxActive: input.cursorMaxActive }); let result; try { result = await executeSql(runtime.sql, runtime.client, { maxRecords: runtime.maxRecords, fetchParallel: runtime.fetchParallel, onLimitReached: runtime.onLimit, cacheContext: runtime.cacheContext, cursorMaxActive: runtime.cursorMaxActive ?? input.cursorMaxActive ?? 2, confirm: async (count, operation) => { if (count > dmlMaxRows) { throw new Error(`ArgumentError: ${operation} affected rows (${count}) exceed dmlMaxRows (${dmlMaxRows}).`); } return true; }, ...importOptions }); } catch (err) { throw selectBasedDml ? appendSelectBasedDmlReadLimitHint(err) : err; } if (result.type === "SELECT" || result.type === "ASSERT" || result.type === "VALIDATION") { throw new Error(`ArgumentError: ksql_mutate returned unexpected result type ${result.type}.`); } return toMutationPayload(result); } async function describeApp(input) { return await query({ sql: `DESCRIBE APP${input.app}`, profile: input.profile, maxRecords: input.maxRecords, fetchParallel: input.fetchParallel, onLimit: input.onLimit, timeout: input.timeout }); } async function appMetadata(input) { const { app, profile: profile2, ...request } = input; let runtime; try { runtime = await createMetadataRuntime(serverOptions, { app, profile: profile2, request }); } catch (err) { throw sanitizeMetadataError(err); } const metadata = runtime.metadata; return { ok: true, type: "KINTONE_METADATA", resource: metadata.resource, environment: metadata.environment, request: { method: "GET", endpoint: metadata.path, app: runtime.sourceApp, resolvedAppId: runtime.resolvedAppId, profile: runtime.profileName, params: metadata.params }, responseBytes: metadata.responseBytes, data: metadata.data }; } async function showApps(input) { return await query({ sql: "SHOW APPS", profile: input.profile, maxRecords: input.maxRecords, fetchParallel: input.fetchParallel, onLimit: input.onLimit, timeout: input.timeout }); } async function saveQuery(input) { const validation = requireSingleStatement( await validate({ sql: input.sql, profile: input.defaultProfile }), "ksql_save_query" ); assertSavedQuerySafety(input, { isDml: validation.isDml, statementType: validation.statementType }); const filePath = getSavedQueryCatalogPath(serverOptions); const catalog = await loadSavedQueryCatalog(filePath); const saved = upsertSavedQuery(catalog, input); await saveSavedQueryCatalog(filePath, saved.catalog); return { ok: true, created: saved.created, query: saved.query }; } async function listQueries(_input = {}) { const catalog = await loadSavedQueryCatalog(getSavedQueryCatalogPath(serverOptions)); return { ok: true, queries: catalog.queries.map((query2) => ({ name: query2.name, title: query2.title, description: query2.description, defaultProfile: query2.defaultProfile, readOnly: query2.readOnly, allowProfileOverride: query2.allowProfileOverride === true, createdAt: query2.createdAt, updatedAt: query2.updatedAt, tags: query2.tags ?? [] })) }; } async function getQuery(input) { const catalog = await loadSavedQueryCatalog(getSavedQueryCatalogPath(serverOptions)); return { ok: true, query: getSavedQuery(catalog, input.name) }; } async function runSavedQuery(input) { const catalog = await loadSavedQueryCatalog(getSavedQueryCatalogPath(serverOptions)); const saved = getSavedQuery(catalog, input.name); assertProfileOverrideAllowed(saved, input.profile); const profile2 = input.profile ?? saved.defaultProfile; const validation = requireSingleStatement( await validate({ sql: saved.sql, profile: profile2 }), "ksql_run_saved_query" ); assertSavedQuerySafety(saved, { isDml: validation.isDml, statementType: validation.statementType }); if (saved.readOnly) { const result2 = await query({ sql: saved.sql, profile: profile2, maxRecords: input.maxRecords, fetchParallel: input.fetchParallel, onLimit: input.onLimit, timeout: input.timeout }, validation); return { ok: true, name: saved.name, result: result2 }; } const dmlMaxRows = requireDmlApproval(input, "ksql_run_saved_query", "for DML saved queries"); const result = await mutate({ sql: saved.sql, profile: profile2, allowDml: true, confirmText: "yes", dmlMaxRows, fetchParallel: input.fetchParallel, timeout: input.timeout }, validation); return { ok: true, name: saved.name, result }; } async function deleteQuery(input) { const filePath = getSavedQueryCatalogPath(serverOptions); const catalog = await loadSavedQueryCatalog(filePath); const deleted = deleteSavedQuery(catalog, input.name); await saveSavedQueryCatalog(filePath, deleted.catalog); return { ok: true, name: input.name, deleted: deleted.deleted }; } return { validate, explain, query, mutate, appMetadata, describeApp, showApps, saveQuery, listQueries, getQuery, runSavedQuery, deleteQuery, validateTool: (input) => runSafely(() => validate(input)), explainTool: (input) => runSafely(() => explain(input)), queryTool: (input) => runSafely(() => query(input)), mutateTool: (input) => runSafely(() => mutate(input)), appMetadataTool: (input) => runSafely( () => appMetadata(ksqlAppMetadataInputSchema.parse(input)) ), describeAppTool: (input) => runSafely(() => describeApp(input)), showAppsTool: (input) => runSafely(() => showApps(input)), saveQueryTool: (input) => runSafely(() => saveQuery(input)), listQueriesTool: (input) => runSafely(() => listQueries(input)), getQueryTool: (input) => runSafely(() => getQuery(input)), runSavedQueryTool: (input) => runSafely(() => runSavedQuery(input)), deleteQueryTool: (input) => runSafely(() => deleteQuery(input)) }; } // src/mcp/statementSyntaxCatalog.ts init_define_KSQL_DOCS(); var STATEMENT_SYNTAX_CHECKS = "CHECKS := [CHECK WHEN cond THEN 'msg' [WHEN ...] ]..."; var STATEMENT_SYNTAX_CONTROL = "CONTROL := [VALIDATE ONLY [INTO #err] | ON ERROR SKIP INTO #err [REJECT LIMIT n]]"; var STATEMENT_SYNTAX_COMMON_NOTES = [ "CHECKS precedes CONTROL. VALIDATE ONLY and ON ERROR SKIP are mutually exclusive.", "INTO #err requires a multi-statement batch (ON ERROR SKIP always; VALIDATE ONLY / VALIDATE only when INTO is used).", "APPLY may precede VALIDATE ONLY but cannot combine with CHECK or ON ERROR SKIP.", "Subtable DML does not accept CHECKS/CONTROL.", "These are all supported top-level statement families. Bracketed clauses are schematic; before first use, verify the referenced ksql_docs section. Do not invent other statement families or clause orders. UPDATE CHECK sees pre-update values; to test the new value, repeat the SET expression inside CHECK. Variable names start with ASCII letter/_; see ksql_docs for placement rules." ]; var STATEMENT_SYNTAX_CATALOG = { select: { template: "SELECT: SELECT[DISTINCT] cols [FROM APPn|APPn$tbl|#t[alias][INNER|LEFT|RIGHT JOIN t[alias]ON a.x=b.y]...][WHERE][GROUP BY][HAVING][ORDER BY|KORDER BY][LIMIT n[OFFSET m]]", examples: ["SELECT 1 AS one"], expectedTypes: [["SELECT"]] }, with: { template: "WITH: WITH name AS(SELECT|SHOW APPS|DESCRIBE...)[,name2 AS(...)]... SELECT|UNION...", examples: ["WITH app_list AS (SHOW APPS), field_list AS (DESCRIBE APP1) SELECT * FROM app_list"], expectedTypes: [["WITH"]] }, union: { template: "UNION: SELECT... UNION[ALL] SELECT...", examples: ["SELECT 1 AS n UNION ALL SELECT 2 AS n"], expectedTypes: [["UNION"]] }, insert: { template: "INSERT: INSERT INTO APPn(cols){VALUES(...)...|SELECT...} CHECKS CONTROL", examples: [ "CREATE TEMP TABLE #source AS SELECT 'C001' AS code; INSERT INTO APP1 (code) SELECT code FROM #source CHECK WHEN code = '' THEN 'required' ON ERROR SKIP INTO #err REJECT LIMIT 10; SELECT * FROM #err" ], expectedTypes: [["CREATE_TEMP_TABLE", "INSERT_SELECT", "SELECT"]], batch: true }, update: { template: "UPDATE: UPDATE APPn SET col=expr,... WHERE... CHECKS CONTROL", examples: [ "UPDATE APP1 SET status = 'done' WHERE $id = 1 CHECK WHEN status = '' THEN 'required' VALIDATE ONLY" ], expectedTypes: [["UPDATE"]] }, updateFrom: { template: "UPDATE-FROM: UPDATE APPn SET col=s.col,... FROM #t|APPm[AS]s WHERE APPn.key=s.key[AND target_condition] CHECKS CONTROL", examples: [ "CREATE TEMP TABLE #source AS SELECT 'C001' AS key, 'done' AS value; UPDATE APP1 SET status = s.value FROM #source AS s WHERE APP1.key = s.key VALIDATE ONLY; DROP TEMP TABLE #source" ], expectedTypes: [["CREATE_TEMP_TABLE", "UPDATE", "DROP_TEMP_TABLE"]], batch: true }, upsert: { template: "UPSERT: UPSERT INTO APPn(cols){VALUES...|SELECT...} ON DUPLICATE(key[,key]...) CHECKS CONTROL", examples: [ "UPSERT INTO APP1 (key, name) VALUES ('C001', 'Acme') ON DUPLICATE (key) VALIDATE ONLY" ], expectedTypes: [["UPSERT"]] }, delete: { template: "DELETE: DELETE FROM APPn WHERE...", examples: ["DELETE FROM APP1 WHERE $id = 1"], expectedTypes: [["DELETE"]] }, subtableDml: { template: "Subtable-DML: INSERT INTO APPn$tbl(_pid,cols)VALUES...|UPDATE APPn$tbl SET... WHERE _pid=...[AND _rid=...]|DELETE FROM APPn$tbl WHERE...", examples: [ "INSERT INTO APP1$details (_pid, item, qty) VALUES (1, 'A-001', 2)", "UPDATE APP1$details SET qty = 5 WHERE _pid = 1 AND _rid = '67890'", "DELETE FROM APP1$details WHERE _pid = 1 AND _rid = '67890'" ], expectedTypes: [["INSERT"], ["UPDATE"], ["DELETE"]] }, apply: { template: "APPLY: UPDATE...WHERE...APPLY tbl(ops)[APPLY...][VALIDATE ONLY]|INSERT...VALUES...APPLY tbl(ops)[VALIDATE ONLY]|UPSERT...ON DUPLICATE(...)[ON INSERT APPLY tbl(ops)][ON UPDATE APPLY tbl(ops)][VALIDATE ONLY]", examples: [ "UPDATE APP1 SET status = 'done' WHERE $id = 1 APPLY details (PATCH SET qty = 0 WHERE qty < 0) VALIDATE ONLY", "INSERT INTO APP1 (name) VALUES ('new') APPLY details (APPEND (item, qty) VALUES ('A-001', 1)) VALIDATE ONLY", "UPSERT INTO APP1 (key, name) VALUES ('C001', 'Acme') ON DUPLICATE (key) ON INSERT APPLY details (APPEND (item) VALUES ('initial')) ON UPDATE APPLY details (REMOVE ALL ROWS) VALIDATE ONLY" ], expectedTypes: [["UPDATE"], ["INSERT"], ["UPSERT"]] }, validate: { template: "VALIDATE: VALIDATE APPn[(fields)][SUMMARY][WHERE...] CHECKS[INTO #err]", examples: [ "VALIDATE APP1 (code) SUMMARY WHERE $id > 0 CHECK WHEN code = '' THEN 'required' INTO #err; SELECT * FROM #err" ], expectedTypes: [["VALIDATE", "SELECT"]], batch: true }, import: { template: "IMPORT: IMPORT[UPDATE] INTO APPn(cols|tbl(children)) FROM CSV|JSON name[options...]", examples: ["IMPORT INTO APP1 (code, name) FROM CSV customers BY NAME VALIDATE ONLY"], expectedTypes: [["IMPORT"]], capabilities: { import: true } }, tempTable: { template: "Temp-table: CREATE TEMP TABLE #t AS SELECT...|AS WITH...|DROP TEMP TABLE #t", examples: [ "CREATE TEMP TABLE #source AS SELECT 1 AS n; SELECT n FROM #source; DROP TEMP TABLE #source" ], expectedTypes: [["CREATE_TEMP_TABLE", "SELECT", "DROP_TEMP_TABLE"]], batch: true }, variables: { template: "Variables: SET @x=scalar_expr|(SELECT...)|['a',...]|DECLARE @x=default", examples: ["SET @x = 1; DECLARE @label = 'ready'; SELECT @x AS x, @label AS label"], expectedTypes: [["SET_VARIABLE", "DECLARE_VARIABLE", "SELECT"]], batch: true }, assert: { template: "ASSERT: ASSERT operand op operand|ASSERT operand BETWEEN a AND b", examples: ["ASSERT 2 BETWEEN 1 AND 3"], expectedTypes: [["ASSERT"]] }, reorder: { template: "REORDER: REORDER APPn$tbl BY... WHERE...|REORDER ALL APPn$tbl BY...", examples: [ "REORDER APP1$details BY item ASC WHERE _pid = 1", "REORDER ALL APP1$details BY item ASC" ], expectedTypes: [["REORDER"], ["REORDER"]] }, showDescribe: { template: "SHOW/DESCRIBE: SHOW APPS|DESCRIBE|DESC APPn", examples: ["SHOW APPS", "DESCRIBE APP1", "DESC APP1"], expectedTypes: [["SHOW_APPS"], ["DESCRIBE"], ["DESCRIBE"]] }, explain: { template: "EXPLAIN: EXPLAIN(SELECT|WITH|INSERT|UPSERT|UPDATE|DELETE|REORDER|VALIDATE|IMPORT)...", examples: [ "EXPLAIN SELECT * FROM APP1", "EXPLAIN WITH source AS (SELECT * FROM APP1) SELECT * FROM source", "EXPLAIN INSERT INTO APP1 (name) VALUES ('Acme')", "EXPLAIN UPSERT INTO APP1 (key) VALUES ('C001') ON DUPLICATE (key)", "EXPLAIN UPDATE APP1 SET status = 'done' WHERE $id = 1", "EXPLAIN DELETE FROM APP1 WHERE $id = 1", "EXPLAIN REORDER APP1$details BY item ASC WHERE _pid = 1", "EXPLAIN VALIDATE APP1", "EXPLAIN IMPORT INTO APP1 (code) FROM JSON payload" ], expectedTypes: Array.from({ length: 9 }, () => ["EXPLAIN"]), capabilities: { import: true } } }; var STATEMENT_SYNTAX_PARAGRAPH = `Statement templates: ${STATEMENT_SYNTAX_CHECKS} ${STATEMENT_SYNTAX_CONTROL}. ${Object.values(STATEMENT_SYNTAX_CATALOG).map((entry) => entry.template).join("; ")}. ${STATEMENT_SYNTAX_COMMON_NOTES.join(" ")}`; // src/mcp/index.ts function parseServerArgs(argv) { const out = { help: false }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "-h" || a === "--help") { out.help = true; continue; } const v = argv[i + 1]; if (a === "--config") { out.configPath = v ?? ""; i++; continue; } if (a === "--profile") { out.profile = v ?? ""; i++; continue; } throw new Error(`ArgumentError: unknown option ${a}`); } return out; } function printHelp() { process.stdout.write(`ksql-mcp - MCP server for kintone-sql-tools Usage: ksql-mcp [options] Options: --config Config file path (default: ./ksql.config.json or KSQL_CONFIG) --profile Default profile name -h, --help Show help IMPORT CSV/JSON is call-scoped and disabled by default. Supply named inline importSources (text or base64 bytes) to enable it; filesystem paths are not accepted. Nested JSON/CSV subtable mutation is fail-closed on MCP: use VALIDATE ONLY/EXPLAIN. JSON child IDs are rejected and replacement renumbers all rows. `); } var SERVER_VERSION = true ? "3.16.0" : "0.0.0-dev"; var FUNCTION_CATALOG_PARAGRAPH = `Complete function catalog \u2014 Scalar: ${KSQL_FUNCTION_CATALOG.scalar.join(" ")}. Aggregate: ${KSQL_FUNCTION_CATALOG.aggregate.join(" ")}. Variance and standard-deviation aggregates use explicit POP/SAMP names; unqualified STDDEV and VARIANCE are unsupported. Window: ${KSQL_FUNCTION_CATALOG.window.join(" ")} (OVER and AS alias required). Contextual: ${KSQL_FUNCTION_CATALOG.contextual.join(" ")} (kintone predicates; LOGINUSER resolves to an empty string in Node/MCP). Aliases: ${KSQL_FUNCTION_CATALOG.aliases.join(" ")}. Syntax: ${KSQL_FUNCTION_CATALOG.syntax.join(" ")}. This list is complete; functions from other dialects such as IFNULL do not exist. Use ksql_docs for arguments and constraints.`; var KSQL_MCP_INSTRUCTIONS = `kSQL is a SQL-like dialect for kintone, not generic SQL. Supports cataloged families plus JOIN, aggregates, windows, subtable virtual tables, CHECK, KLIKE, KORDER BY, @variables, and LAPP_. Key rules: LIKE/NOT LIKE uses JavaScript semantics; JOIN ON allows one equality; derived tables are unsupported (use WITH/temp tables); empty numeric cells become 0 in arithmetic. APPLY supports validation, EXPLAIN, and VALIDATE ONLY; APPLY mutation is disabled in MCP. Use ksql_validate before execution. Before DML, use ksql_query VALIDATE ONLY and ksql_app_metadata, then ksql_mutate. Before first use of a statement form, verify it in ksql_docs; never invent syntax. Read ksql://language-reference or ksql://recipes; if unavailable, call ksql_docs without arguments, then only needed sections. Never probe ksql_validate to discover functions or syntax. ${STATEMENT_SYNTAX_PARAGRAPH} ${FUNCTION_CATALOG_PARAGRAPH}`; var MARKDOWN_MIME_TYPE = "text/markdown"; function staticTextResource(uri, text) { return { contents: [{ uri, mimeType: MARKDOWN_MIME_TYPE, text }] }; } function requiredTemplateKey(value, kind) { if (typeof value !== "string") { throw new McpError(ErrorCode.InvalidParams, `Invalid ${kind} resource key.`); } return value; } function invalidResourceKey(kind, key) { throw new McpError(ErrorCode.InvalidParams, `Unknown kSQL ${kind} resource key: ${key}`); } function toDocsSuccessResult(text) { return { content: [{ type: "text", text }] }; } function toDocsErrorResult(err) { return toToolResult(toErrorPayload(err), true); } function createServer(args) { const server = new McpServer( { name: "ksql-mcp", version: SERVER_VERSION }, { instructions: KSQL_MCP_INSTRUCTIONS } ); const tools = createKsqlMcpTools({ configPath: args.configPath, profile: args.profile }); server.registerTool("ksql_validate", { title: "Validate kSQL", description: "Parse and validate kSQL without calling kintone APIs. All APPLY forms (UPDATE/INSERT/UPSERT/multi-value) are accepted for syntax and static validation, but this does not enable APPLY mutation. Use this before executing generated SQL. Do not use validate probing to discover functions or syntax; call ksql_docs instead. IMPORT CSV/JSON is enabled only when named inline importSources are supplied.", inputSchema: validateInputShape }, tools.validateTool); server.registerTool("ksql_explain", { title: "Explain kSQL", description: "Return the schema-aware kSQL execution plan, including every APPLY form (UPDATE/INSERT/UPSERT/multi-value). Reads form metadata and, when needed, process status metadata; never calls records or mutation APIs. IMPORT CSV/JSON is enabled only when named inline importSources are supplied.", inputSchema: explainInputShape }, tools.explainTool); server.registerTool("ksql_query", { title: "Run read-only kSQL", description: "Execute read-only kSQL: SELECT, WITH, UNION, EXPLAIN, SHOW APPS, DESCRIBE, ASSERT, leading VALIDATE app existing-record audits, and INSERT/UPSERT/UPDATE ... VALIDATE ONLY. Read-only validation tails are DML ... VALIDATE ONLY [INTO #err] and leading VALIDATE APPn ... [INTO #err]; INTO is batch-only. ASSERT failure always stops the batch. Local ORDER BY plans require complete input and fail instead of returning a truncated top-N; REST top-N and KORDER_NATIVE do not fetch a partial candidate set. VALIDATE and VALIDATE ONLY always treat onLimit=truncate as error and perform zero write API calls. UPDATE/INSERT/UPSERT/multi-value APPLY VALIDATE ONLY evaluates dmlMaxSubtableRows with the fixed default 500; ksql_query does not expose an override. Existing-record VALIDATE applies built-in form constraints plus optional CHECK groups and can materialize its fixed five diagnostic columns with INTO #err in a batch. NUMBER targets use the app numberPrecision settings for integer-digit validation and fail closed if settings cannot be read. Excess fractional digits pass through for kintone to round automatically. Supports multi-statement batches with temp tables, including VALIDATE ONLY INTO #err for later SELECT. APPLY mutation remains fail-closed; mutating DML is rejected. For kSQL dialect details, follow the server instructions and read ksql://language-reference (or call ksql_docs when resources are unavailable).", inputSchema: queryInputShape }, tools.queryTool); server.registerTool("ksql_mutate", { title: "Run mutating kSQL (IMPORT CSV/JSON via importSources)", description: "Execute DML kSQL with explicit allowDml, confirmText, and dmlMaxRows safety controls. Common DML tail: {VALUES|SELECT} CHECKS \u2192 [VALIDATE ONLY [INTO #err] | ON ERROR SKIP INTO #err [REJECT LIMIT n]]. INTO forms are available only in a multi-statement batch. UPDATE CHECK evaluates pre-update values; repeat the SET expression to test new values. Every APPLY mutation form (UPDATE/INSERT/UPSERT/multi-value) is always rejected by MCP v3.8.0 before runtime or records API creation; allowDml and dmlMaxSubtableRows do not enable it. Supports multi-statement DML batches with temp tables. ON ERROR SKIP INTO #err optionally isolates local Tier-0 validation failures and writes only valid rows; REJECT LIMIT stops with zero writes while returning diagnostics. NUMBER targets use the destination app numberPrecision settings for integer-digit validation in normal, validation-only, and skip paths; settings failures are fail-closed. Excess fractional digits pass through for kintone to round automatically. INSERT/UPSERT INTO app ... SELECT supports app sources, temp tables, or joins of both. UPDATE ... FROM supports copying scalar fields from an app or temp table by matching target $id or a single-line-text/number business key to one source key. For UPSERT, dmlMaxRows counts inserts + updates. dmlMaxRows caps affected rows only, not source reads: source SELECT, ON ERROR SKIP candidates, and UPDATE ... FROM app reads use the runtime maxRecords (KSQL_MAX_RECORDS / profile query.maxRecords, default 500); temp tables hold at most 10000 rows by default (adjustable via tempTableMaxRows). For kSQL dialect details, follow the server instructions and read ksql://language-reference (or call ksql_docs when resources are unavailable).", inputSchema: mutateInputShape }, tools.mutateTool); server.registerTool("ksql_describe_app", { title: "Describe kintone app", description: "Return kSQL's compact field list (field code, label, and type) for a kintone app. For complete raw field constraints, layout, settings, status, views, reports, or customize metadata, use ksql_app_metadata.", inputSchema: describeAppInputShape }, tools.describeAppTool); server.registerTool("ksql_app_metadata", { title: "Get kintone app metadata", description: "Inspect raw read-only kintone app metadata before generating SQL or DML: app, fields (constraints and field properties), layout, settings, status, views, reports, and customize. This is the primary route for constraints not included in ksql_describe_app. Returns raw JSON through a fixed GET allowlist; records and mutation operations are not available.", inputSchema: ksqlAppMetadataInputShape }, tools.appMetadataTool); server.registerTool("ksql_show_apps", { title: "Show kintone apps", description: "Return the full app list (id, name, description) for the selected profile using SHOW APPS. This enumerates every app and can be large on big domains; use it only to discover an unknown app id by name. When you already know the target app, fetch just that one with ksql_app_metadata (resource=app for basics via GET /k/v1/app.json, or fields/settings for constraints) instead of listing all apps.", inputSchema: showAppsInputShape }, tools.showAppsTool); server.registerTool("ksql_docs", { title: "Read kSQL documentation", description: "Read the embedded kSQL language reference and recipes through a read-only tool when MCP resources are unavailable. Call without arguments for the complete section index.", inputSchema: ksqlDocsInputShape, annotations: { readOnlyHint: true, openWorldHint: false } }, ({ section }) => { try { return toDocsSuccessResult(resolveKsqlDocsSection(section)); } catch (err) { return toDocsErrorResult(err); } }); server.registerTool("ksql_save_query", { title: "Save kSQL query", description: "Save a validated kSQL statement into the local saved query catalog.", inputSchema: saveQueryInputShape }, tools.saveQueryTool); server.registerTool("ksql_list_queries", { title: "List saved kSQL queries", description: "List saved kSQL query metadata from the local saved query catalog.", inputSchema: listQueriesInputShape }, tools.listQueriesTool); server.registerTool("ksql_get_query", { title: "Get saved kSQL query", description: "Return a saved kSQL query, including SQL text, by name.", inputSchema: savedQueryNameInputShape }, tools.getQueryTool); server.registerTool("ksql_run_saved_query", { title: "Run saved kSQL query", description: "Run a saved kSQL query. Read-only queries use ksql_query safety; DML queries require ksql_mutate safety inputs.", inputSchema: runSavedQueryInputShape }, tools.runSavedQueryTool); server.registerTool("ksql_delete_query", { title: "Delete saved kSQL query", description: "Delete a saved kSQL query from the local saved query catalog.", inputSchema: savedQueryNameInputShape }, tools.deleteQueryTool); server.registerResource("ksql-language-reference", "ksql://language-reference", { description: "Index of kSQL syntax, dialect rules, and section resources.", mimeType: MARKDOWN_MIME_TYPE }, () => staticTextResource("ksql://language-reference", KSQL_DOCS.languageReference.index)); server.registerResource("ksql-recipes", "ksql://recipes", { description: "Index of safe, rerunnable kSQL batch recipes.", mimeType: MARKDOWN_MIME_TYPE }, () => staticTextResource("ksql://recipes", KSQL_DOCS.recipes.index)); server.registerResource( "ksql-language-reference-section", new ResourceTemplate("ksql://language-reference/{section}", { list: void 0, complete: { section: (value) => LANGUAGE_SECTION_KEYS.filter((key) => key.startsWith(value)) } }), { description: "One allowlisted chapter of the embedded kSQL language reference.", mimeType: MARKDOWN_MIME_TYPE }, (uri, variables) => { const key = requiredTemplateKey(variables.section, "language-reference section"); const section = KSQL_DOCS.languageReference.sections[key]; if (!section) invalidResourceKey("language-reference section", key); return staticTextResource(uri.href, section.text); } ); server.registerResource( "ksql-recipe", new ResourceTemplate("ksql://recipes/{recipe}", { list: void 0, complete: { recipe: (value) => RECIPE_KEYS.filter((key) => key.startsWith(value)) } }), { description: "One allowlisted chapter of the embedded kSQL batch recipes.", mimeType: MARKDOWN_MIME_TYPE }, (uri, variables) => { const key = requiredTemplateKey(variables.recipe, "recipe"); const recipe = KSQL_DOCS.recipes.sections[key]; if (!recipe) invalidResourceKey("recipe", key); return staticTextResource(uri.href, recipe.text); } ); return server; } async function main() { const args = parseServerArgs(process.argv.slice(2)); if (args.help) { printHelp(); return; } const server = createServer(args); const transport = new StdioServerTransport(); await server.connect(transport); } if (require.main === module) { main().catch((err) => { process.stderr.write(`${err instanceof Error ? err.message : String(err)} `); process.exitCode = 1; }); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { KSQL_MCP_INSTRUCTIONS, createServer, main });