@rebasepro/server-postgres 0.11.1-canary.gfd39654 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PostgresBootstrapper.d.ts +8 -0
- package/dist/collections/buildRegistry.d.ts +1 -1
- package/dist/{ensure-collection-tables-DGMYK0fr.js → ensure-collection-tables-CNTcZGvn.js} +3 -3
- package/dist/{ensure-collection-tables-DGMYK0fr.js.map → ensure-collection-tables-CNTcZGvn.js.map} +1 -1
- package/dist/history/HistoryService.d.ts +9 -29
- package/dist/index.es.js +397 -53
- package/dist/index.es.js.map +1 -1
- package/dist/schema/dynamic-tables.d.ts +1 -1
- package/dist/schema/introspect-runtime.d.ts +1 -1
- package/dist/services/FetchService.d.ts +36 -1
- package/dist/services/row-pipeline.d.ts +3 -1
- package/dist/{src-3VmUJ8Xn.js → src-BbFOPJ1S.js} +197 -18
- package/dist/src-BbFOPJ1S.js.map +1 -0
- package/dist/{src-D5xBTl32.js → src-Zqwaw3P5.js} +136 -90
- package/dist/src-Zqwaw3P5.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +157 -3
- package/dist/utils/pg-error-utils.d.ts +6 -3
- package/package.json +6 -6
- package/src/PostgresBootstrapper.ts +23 -6
- package/src/collections/buildRegistry.ts +1 -1
- package/src/history/HistoryService.ts +13 -31
- package/src/schema/dynamic-tables.ts +1 -1
- package/src/schema/generate-drizzle-schema-logic.ts +10 -2
- package/src/schema/introspect-runtime.ts +1 -1
- package/src/services/FetchService.ts +79 -11
- package/src/services/row-pipeline.ts +3 -1
- package/src/utils/drizzle-conditions.ts +509 -45
- package/src/utils/pg-error-utils.ts +52 -3
- package/dist/src-3VmUJ8Xn.js.map +0 -1
- package/dist/src-D5xBTl32.js.map +0 -1
package/dist/src-3VmUJ8Xn.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-3VmUJ8Xn.js","names":[],"sources":["../../common/src/util/common.ts","../../utils/src/strings.ts","../../../node_modules/.pnpm/object-hash@3.0.0/node_modules/object-hash/dist/object_hash.js","../../utils/src/objects.ts","../../utils/src/sha1.ts","../../utils/src/policy-names.ts","../../utils/src/names.ts","../../common/src/util/entities.ts","../../common/src/util/identity.ts","../../common/src/util/enums.ts","../../common/src/util/resolve-relation.ts","../../common/src/util/relations.ts","../../common/src/util/resolutions.ts","../../common/src/util/policy/sqlToPolicy.ts","../../common/src/util/policy/securityRuleToConditions.ts","../../common/src/util/policy/policyToPostgres.ts","../../common/src/util/builders.ts","../../common/src/util/callbacks.ts","../../common/src/util/auth-default-policies.ts","../../common/src/util/junction-policies.ts","../../../node_modules/.pnpm/json-logic-js@2.0.5/node_modules/json-logic-js/logic.js","../../common/src/util/conditions.ts","../../../node_modules/.pnpm/fast-equals@6.0.0/node_modules/fast-equals/dist/es/index.mjs","../../common/src/data/resolveDataSource.ts","../../common/src/collections/CollectionRegistry.ts","../../common/src/collections/default-collections.ts","../../common/src/data/query_builder.ts","../../common/src/data/filter-dialect.ts","../../common/src/data/buildRebaseData.ts","../../common/src/table-classification.ts"],"sourcesContent":["export const DEFAULT_ONE_OF_TYPE = \"type\"\nexport const DEFAULT_ONE_OF_VALUE = \"value\"\n","const tokenizeRegex = /[A-Z]{2,}(?=[A-Z][a-z]|\\b)|[A-Z]?[a-z]+|[0-9]+(?:[a-z](?![a-z]))?|[A-Z]/g;\n\nexport const toKebabCase = (str?: string) => {\n if (!str || typeof str !== \"string\") return \"\";\n const regExpMatchArray = str.match(tokenizeRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"-\");\n};\n\nconst snakeCaseRegex = tokenizeRegex;\n\nexport const toSnakeCase = (str?: string) => {\n if (!str || typeof str !== \"string\") return \"\";\n const regExpMatchArray = str.match(snakeCaseRegex);\n if (!regExpMatchArray) return \"\";\n return regExpMatchArray\n .map(x => x.toLowerCase())\n .join(\"_\");\n};\n\nexport function camelCase(str: string): string {\n if (!str) return \"\";\n if (str.length === 1) return str.toLowerCase();\n\n // Split by hyphens, underscores, or spaces and filter out empty strings\n const parts = str.split(/[-_ ]+/).filter(Boolean);\n\n if (parts.length === 0) return \"\";\n\n // Start with first part in lowercase\n return parts[0].toLowerCase() +\n // Transform remaining parts to have first letter uppercase\n parts.slice(1)\n .map(part => part.charAt(0).toUpperCase() + part.substring(1).toLowerCase())\n .join(\"\");\n}\n\n/**\n * A random base-36 string of exactly `strLength` characters.\n *\n * Not `Math.random().toString(36).slice(2, 2 + strLength)`: that has no\n * guaranteed length. Base-36 of a double drops trailing zeros, so the source\n * string is short about once in 36 calls and the slice quietly returns fewer\n * characters than asked for — `randomString(10)` returning 9. These values\n * prefix uploaded filenames to keep them apart, so a short one is a likelier\n * collision, and it fails at the rate that makes a test look flaky.\n */\nexport function randomString(strLength = 5) {\n const alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n let result = \"\";\n for (let i = 0; i < strLength; i++) {\n result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));\n }\n return result;\n}\n\nexport function randomColor() {\n return Math.floor(Math.random() * 16777215).toString(16);\n}\n\nexport function slugify(text?: string, separator = \"_\", lowercase = true) {\n if (!text) return \"\";\n const from = \"ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;-\"\n const to = `aaaaaeeeeeiiiiooooouuuunc${separator}${separator}${separator}${separator}${separator}${separator}${separator}`;\n\n for (let i = 0, l = from.length; i < l; i++) {\n text = text.replace(new RegExp(from.charAt(i), \"g\"), to.charAt(i));\n }\n\n text = text\n .toString() // Cast to string\n .trim() // Remove whitespace from both sides of a string\n .replace(/^\\s+|\\s+$/g, \"\")\n .replace(/\\s+/g, separator) // Replace spaces with separator\n .replace(/&/g, separator) // Replace & with separator\n .replace(/[^\\w\\\\-]+/g, \"\") // Remove all non-word chars\n .replace(new RegExp(\"\\\\\" + separator + \"\\\\\" + separator + \"+\", \"g\"),\n separator); // Replace multiple separators with single one\n\n return lowercase\n ? text.toLowerCase() // Convert the string to lowercase letters\n : text;\n}\n\nexport function unslugify(slug?: string): string {\n if (!slug) return \"\";\n if (slug.includes(\"-\") || slug.includes(\"_\") || !slug.includes(\" \")) {\n const result = slug.replace(/[-_]/g, \" \");\n return result.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substring(1);\n }).trim();\n } else {\n return slug.trim();\n }\n}\n\nexport function prettifyIdentifier(input: string) {\n if (!input) return \"\";\n\n let text = input;\n\n // 1. Handle camelCase and Acronyms\n // Group 1 ($1 $2): Lowercase followed by Uppercase (e.g., imageURL -> image URL)\n // Group 2 ($3 $4): Uppercase followed by Uppercase+lowercase (e.g., XMLParser -> XML Parser)\n text = text.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3 $2$4\");\n\n // 2. Replace hyphens/underscores with spaces\n text = text.replace(/[_-]+/g, \" \");\n\n // 3. Capitalize first letter of each word (Title Case)\n const s = text\n .trim()\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n return s;\n}\n","!function(e){var t;\"object\"==typeof exports?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(\"undefined\"!=typeof window?t=window:\"undefined\"!=typeof global?t=global:\"undefined\"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function r(o,i,u){function s(n,e){if(!i[n]){if(!o[n]){var t=\"function\"==typeof require&&require;if(!e&&t)return t(n,!0);if(a)return a(n,!0);throw new Error(\"Cannot find module '\"+n+\"'\")}e=i[n]={exports:{}};o[n][0].call(e.exports,function(e){var t=o[n][1][e];return s(t||e)},e,e.exports,r,o,i,u)}return i[n].exports}for(var a=\"function\"==typeof require&&require,e=0;e<u.length;e++)s(u[e]);return s}({1:[function(w,b,m){!function(e,n,s,c,d,h,p,g,y){\"use strict\";var r=w(\"crypto\");function t(e,t){t=u(e,t);var n;return void 0===(n=\"passthrough\"!==t.algorithm?r.createHash(t.algorithm):new l).write&&(n.write=n.update,n.end=n.update),f(t,n).dispatch(e),n.update||n.end(\"\"),n.digest?n.digest(\"buffer\"===t.encoding?void 0:t.encoding):(e=n.read(),\"buffer\"!==t.encoding?e.toString(t.encoding):e)}(m=b.exports=t).sha1=function(e){return t(e)},m.keys=function(e){return t(e,{excludeValues:!0,algorithm:\"sha1\",encoding:\"hex\"})},m.MD5=function(e){return t(e,{algorithm:\"md5\",encoding:\"hex\"})},m.keysMD5=function(e){return t(e,{algorithm:\"md5\",encoding:\"hex\",excludeValues:!0})};var o=r.getHashes?r.getHashes().slice():[\"sha1\",\"md5\"],i=(o.push(\"passthrough\"),[\"buffer\",\"hex\",\"binary\",\"base64\"]);function u(e,t){var n={};if(n.algorithm=(t=t||{}).algorithm||\"sha1\",n.encoding=t.encoding||\"hex\",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error(\"Object argument required.\");for(var r=0;r<o.length;++r)o[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=o[r]);if(-1===o.indexOf(n.algorithm))throw new Error('Algorithm \"'+n.algorithm+'\" not supported. supported values: '+o.join(\", \"));if(-1===i.indexOf(n.encoding)&&\"passthrough\"!==n.algorithm)throw new Error('Encoding \"'+n.encoding+'\" not supported. supported values: '+i.join(\", \"));return n}function a(e){if(\"function\"==typeof e)return null!=/^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$/i.exec(Function.prototype.toString.call(e))}function f(o,t,i){i=i||[];function u(e){return t.update?t.update(e,\"utf8\"):t.write(e,\"utf8\")}return{dispatch:function(e){return this[\"_\"+(null===(e=o.replacer?o.replacer(e):e)?\"null\":typeof e)](e)},_object:function(t){var n,e=Object.prototype.toString.call(t),r=/\\[object (.*)\\]/i.exec(e);r=(r=r?r[1]:\"unknown:[\"+e+\"]\").toLowerCase();if(0<=(e=i.indexOf(t)))return this.dispatch(\"[CIRCULAR:\"+e+\"]\");if(i.push(t),void 0!==s&&s.isBuffer&&s.isBuffer(t))return u(\"buffer:\"),u(t);if(\"object\"===r||\"function\"===r||\"asyncfunction\"===r)return e=Object.keys(t),o.unorderedObjects&&(e=e.sort()),!1===o.respectType||a(t)||e.splice(0,0,\"prototype\",\"__proto__\",\"constructor\"),o.excludeKeys&&(e=e.filter(function(e){return!o.excludeKeys(e)})),u(\"object:\"+e.length+\":\"),n=this,e.forEach(function(e){n.dispatch(e),u(\":\"),o.excludeValues||n.dispatch(t[e]),u(\",\")});if(!this[\"_\"+r]){if(o.ignoreUnknown)return u(\"[\"+r+\"]\");throw new Error('Unknown object type \"'+r+'\"')}this[\"_\"+r](t)},_array:function(e,t){t=void 0!==t?t:!1!==o.unorderedArrays;var n=this;if(u(\"array:\"+e.length+\":\"),!t||e.length<=1)return e.forEach(function(e){return n.dispatch(e)});var r=[],t=e.map(function(e){var t=new l,n=i.slice();return f(o,t,n).dispatch(e),r=r.concat(n.slice(i.length)),t.read().toString()});return i=i.concat(r),t.sort(),this._array(t,!1)},_date:function(e){return u(\"date:\"+e.toJSON())},_symbol:function(e){return u(\"symbol:\"+e.toString())},_error:function(e){return u(\"error:\"+e.toString())},_boolean:function(e){return u(\"bool:\"+e.toString())},_string:function(e){u(\"string:\"+e.length+\":\"),u(e.toString())},_function:function(e){u(\"fn:\"),a(e)?this.dispatch(\"[native]\"):this.dispatch(e.toString()),!1!==o.respectFunctionNames&&this.dispatch(\"function-name:\"+String(e.name)),o.respectFunctionProperties&&this._object(e)},_number:function(e){return u(\"number:\"+e.toString())},_xml:function(e){return u(\"xml:\"+e.toString())},_null:function(){return u(\"Null\")},_undefined:function(){return u(\"Undefined\")},_regexp:function(e){return u(\"regex:\"+e.toString())},_uint8array:function(e){return u(\"uint8array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return u(\"uint8clampedarray:\"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return u(\"int8array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return u(\"uint16array:\"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return u(\"int16array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return u(\"uint32array:\"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return u(\"int32array:\"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return u(\"float32array:\"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return u(\"float64array:\"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return u(\"arraybuffer:\"),this.dispatch(new Uint8Array(e))},_url:function(e){return u(\"url:\"+e.toString())},_map:function(e){u(\"map:\");e=Array.from(e);return this._array(e,!1!==o.unorderedSets)},_set:function(e){u(\"set:\");e=Array.from(e);return this._array(e,!1!==o.unorderedSets)},_file:function(e){return u(\"file:\"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(o.ignoreUnknown)return u(\"[blob]\");throw Error('Hashing Blob objects is currently not supported\\n(see https://github.com/puleos/object-hash/issues/26)\\nUse \"options.replacer\" or \"options.ignoreUnknown\"\\n')},_domwindow:function(){return u(\"domwindow\")},_bigint:function(e){return u(\"bigint:\"+e.toString())},_process:function(){return u(\"process\")},_timer:function(){return u(\"timer\")},_pipe:function(){return u(\"pipe\")},_tcp:function(){return u(\"tcp\")},_udp:function(){return u(\"udp\")},_tty:function(){return u(\"tty\")},_statwatcher:function(){return u(\"statwatcher\")},_securecontext:function(){return u(\"securecontext\")},_connection:function(){return u(\"connection\")},_zlib:function(){return u(\"zlib\")},_context:function(){return u(\"context\")},_nodescript:function(){return u(\"nodescript\")},_httpparser:function(){return u(\"httpparser\")},_dataview:function(){return u(\"dataview\")},_signal:function(){return u(\"signal\")},_fsevent:function(){return u(\"fsevent\")},_tlswrap:function(){return u(\"tlswrap\")}}}function l(){return{buf:\"\",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}m.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),f(t=u(e,t),n).dispatch(e)}}.call(this,w(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},w(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/fake_9a5aa49d.js\",\"/\")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){!function(e){\"use strict\";var a=\"undefined\"!=typeof Uint8Array?Uint8Array:Array,t=\"+\".charCodeAt(0),n=\"/\".charCodeAt(0),r=\"0\".charCodeAt(0),o=\"a\".charCodeAt(0),i=\"A\".charCodeAt(0),u=\"-\".charCodeAt(0),s=\"_\".charCodeAt(0);function f(e){e=e.charCodeAt(0);return e===t||e===u?62:e===n||e===s?63:e<r?-1:e<r+10?e-r+26+26:e<i+26?e-i:e<o+26?e-o+26:void 0}e.toByteArray=function(e){var t,n;if(0<e.length%4)throw new Error(\"Invalid string. Length must be a multiple of 4\");var r=e.length,r=\"=\"===e.charAt(r-2)?2:\"=\"===e.charAt(r-1)?1:0,o=new a(3*e.length/4-r),i=0<r?e.length-4:e.length,u=0;function s(e){o[u++]=e}for(t=0;t<i;t+=4,0)s((16711680&(n=f(e.charAt(t))<<18|f(e.charAt(t+1))<<12|f(e.charAt(t+2))<<6|f(e.charAt(t+3))))>>16),s((65280&n)>>8),s(255&n);return 2==r?s(255&(n=f(e.charAt(t))<<2|f(e.charAt(t+1))>>4)):1==r&&(s((n=f(e.charAt(t))<<10|f(e.charAt(t+1))<<4|f(e.charAt(t+2))>>2)>>8&255),s(255&n)),o},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u=\"\";function s(e){return\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)n=(e[t]<<16)+(e[t+1]<<8)+e[t+2],u+=s((o=n)>>18&63)+s(o>>12&63)+s(o>>6&63)+s(63&o);switch(i){case 1:u=(u+=s((n=e[e.length-1])>>2))+s(n<<4&63)+\"==\";break;case 2:u=(u=(u+=s((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+s(n>>4&63))+s(n<<2&63)+\"=\"}return u}}(void 0===f?this.base64js={}:f)}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js\",\"/node_modules/gulp-browserify/node_modules/base64-js/lib\")},{buffer:3,lYpoI2:11}],3:[function(O,e,H){!function(e,n,f,r,h,p,g,y,w){var a=O(\"base64-js\"),i=O(\"ieee754\");function f(e,t,n){if(!(this instanceof f))return new f(e,t,n);var r,o,i,u,s=typeof e;if(\"base64\"===t&&\"string\"==s)for(e=(u=e).trim?u.trim():u.replace(/^\\s+|\\s+$/g,\"\");e.length%4!=0;)e+=\"=\";if(\"number\"==s)r=j(e);else if(\"string\"==s)r=f.byteLength(e,t);else{if(\"object\"!=s)throw new Error(\"First argument needs to be a number, array or string.\");r=j(e.length)}if(f._useTypedArrays?o=f._augment(new Uint8Array(r)):((o=this).length=r,o._isBuffer=!0),f._useTypedArrays&&\"number\"==typeof e.byteLength)o._set(e);else if(C(u=e)||f.isBuffer(u)||u&&\"object\"==typeof u&&\"number\"==typeof u.length)for(i=0;i<r;i++)f.isBuffer(e)?o[i]=e.readUInt8(i):o[i]=e[i];else if(\"string\"==s)o.write(e,0,t);else if(\"number\"==s&&!f._useTypedArrays&&!n)for(i=0;i<r;i++)o[i]=0;return o}function b(e,t,n,r){return f._charsWritten=c(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function m(e,t,n,r){return f._charsWritten=c(function(e){for(var t,n,r=[],o=0;o<e.length;o++)n=e.charCodeAt(o),t=n>>8,n=n%256,r.push(n),r.push(t);return r}(t),e,n,r)}function v(e,t,n){var r=\"\";n=Math.min(e.length,n);for(var o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r}function o(e,t,n,r){r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+1<e.length,\"Trying to read beyond buffer length\"));var o,r=e.length;if(!(r<=t))return n?(o=e[t],t+1<r&&(o|=e[t+1]<<8)):(o=e[t]<<8,t+1<r&&(o|=e[t+1])),o}function u(e,t,n,r){r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+3<e.length,\"Trying to read beyond buffer length\"));var o,r=e.length;if(!(r<=t))return n?(t+2<r&&(o=e[t+2]<<16),t+1<r&&(o|=e[t+1]<<8),o|=e[t],t+3<r&&(o+=e[t+3]<<24>>>0)):(t+1<r&&(o=e[t+1]<<16),t+2<r&&(o|=e[t+2]<<8),t+3<r&&(o|=e[t+3]),o+=e[t]<<24>>>0),o}function _(e,t,n,r){if(r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+1<e.length,\"Trying to read beyond buffer length\")),!(e.length<=t))return r=o(e,t,n,!0),32768&r?-1*(65535-r+1):r}function E(e,t,n,r){if(r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+3<e.length,\"Trying to read beyond buffer length\")),!(e.length<=t))return r=u(e,t,n,!0),2147483648&r?-1*(4294967295-r+1):r}function I(e,t,n,r){return r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(t+3<e.length,\"Trying to read beyond buffer length\")),i.read(e,t,n,23,4)}function A(e,t,n,r){return r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(t+7<e.length,\"Trying to read beyond buffer length\")),i.read(e,t,n,52,8)}function s(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+1<e.length,\"trying to write beyond buffer length\"),Y(t,65535));o=e.length;if(!(o<=n))for(var i=0,u=Math.min(o-n,2);i<u;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function l(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"trying to write beyond buffer length\"),Y(t,4294967295));o=e.length;if(!(o<=n))for(var i=0,u=Math.min(o-n,4);i<u;i++)e[n+i]=t>>>8*(r?i:3-i)&255}function B(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+1<e.length,\"Trying to write beyond buffer length\"),F(t,32767,-32768)),e.length<=n||s(e,0<=t?t:65535+t+1,n,r,o)}function L(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"Trying to write beyond buffer length\"),F(t,2147483647,-2147483648)),e.length<=n||l(e,0<=t?t:4294967295+t+1,n,r,o)}function U(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"Trying to write beyond buffer length\"),D(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||i.write(e,t,n,r,23,4)}function x(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+7<e.length,\"Trying to write beyond buffer length\"),D(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||i.write(e,t,n,r,52,8)}H.Buffer=f,H.SlowBuffer=f,H.INSPECT_MAX_BYTES=50,f.poolSize=8192,f._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&\"function\"==typeof t.subarray}catch(e){return!1}}(),f.isEncoding=function(e){switch(String(e).toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"raw\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return!0;default:return!1}},f.isBuffer=function(e){return!(null==e||!e._isBuffer)},f.byteLength=function(e,t){var n;switch(e+=\"\",t||\"utf8\"){case\"hex\":n=e.length/2;break;case\"utf8\":case\"utf-8\":n=T(e).length;break;case\"ascii\":case\"binary\":case\"raw\":n=e.length;break;case\"base64\":n=M(e).length;break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":n=2*e.length;break;default:throw new Error(\"Unknown encoding\")}return n},f.concat=function(e,t){if(d(C(e),\"Usage: Buffer.concat(list, [totalLength])\\nlist should be an Array.\"),0===e.length)return new f(0);if(1===e.length)return e[0];if(\"number\"!=typeof t)for(o=t=0;o<e.length;o++)t+=e[o].length;for(var n=new f(t),r=0,o=0;o<e.length;o++){var i=e[o];i.copy(n,r),r+=i.length}return n},f.prototype.write=function(e,t,n,r){isFinite(t)?isFinite(n)||(r=n,n=void 0):(a=r,r=t,t=n,n=a),t=Number(t)||0;var o,i,u,s,a=this.length-t;switch((!n||a<(n=Number(n)))&&(n=a),r=String(r||\"utf8\").toLowerCase()){case\"hex\":o=function(e,t,n,r){n=Number(n)||0;var o=e.length-n;(!r||o<(r=Number(r)))&&(r=o),d((o=t.length)%2==0,\"Invalid hex string\"),o/2<r&&(r=o/2);for(var i=0;i<r;i++){var u=parseInt(t.substr(2*i,2),16);d(!isNaN(u),\"Invalid hex string\"),e[n+i]=u}return f._charsWritten=2*i,i}(this,e,t,n);break;case\"utf8\":case\"utf-8\":i=this,u=t,s=n,o=f._charsWritten=c(T(e),i,u,s);break;case\"ascii\":case\"binary\":o=b(this,e,t,n);break;case\"base64\":i=this,u=t,s=n,o=f._charsWritten=c(M(e),i,u,s);break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":o=m(this,e,t,n);break;default:throw new Error(\"Unknown encoding\")}return o},f.prototype.toString=function(e,t,n){var r,o,i,u,s=this;if(e=String(e||\"utf8\").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):s.length)===t)return\"\";switch(e){case\"hex\":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||r<n)&&(n=r);for(var o=\"\",i=t;i<n;i++)o+=k(e[i]);return o}(s,t,n);break;case\"utf8\":case\"utf-8\":r=function(e,t,n){var r=\"\",o=\"\";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=N(o)+String.fromCharCode(e[i]),o=\"\"):o+=\"%\"+e[i].toString(16);return r+N(o)}(s,t,n);break;case\"ascii\":case\"binary\":r=v(s,t,n);break;case\"base64\":o=s,u=n,r=0===(i=t)&&u===o.length?a.fromByteArray(o):a.fromByteArray(o.slice(i,u));break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":r=function(e,t,n){for(var r=e.slice(t,n),o=\"\",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}(s,t,n);break;default:throw new Error(\"Unknown encoding\")}return r},f.prototype.toJSON=function(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}},f.prototype.copy=function(e,t,n,r){if(t=t||0,(r=r||0===r?r:this.length)!==(n=n||0)&&0!==e.length&&0!==this.length){d(n<=r,\"sourceEnd < sourceStart\"),d(0<=t&&t<e.length,\"targetStart out of bounds\"),d(0<=n&&n<this.length,\"sourceStart out of bounds\"),d(0<=r&&r<=this.length,\"sourceEnd out of bounds\"),r>this.length&&(r=this.length);var o=(r=e.length-t<r-n?e.length-t+n:r)-n;if(o<100||!f._useTypedArrays)for(var i=0;i<o;i++)e[i+t]=this[i+n];else e._set(this.subarray(n,n+o),t)}},f.prototype.slice=function(e,t){var n=this.length;if(e=S(e,n,0),t=S(t,n,n),f._useTypedArrays)return f._augment(this.subarray(e,t));for(var r=t-e,o=new f(r,void 0,!0),i=0;i<r;i++)o[i]=this[i+e];return o},f.prototype.get=function(e){return console.log(\".get() is deprecated. Access using array indexes instead.\"),this.readUInt8(e)},f.prototype.set=function(e,t){return console.log(\".set() is deprecated. Access using array indexes instead.\"),this.writeUInt8(e,t)},f.prototype.readUInt8=function(e,t){if(t||(d(null!=e,\"missing offset\"),d(e<this.length,\"Trying to read beyond buffer length\")),!(e>=this.length))return this[e]},f.prototype.readUInt16LE=function(e,t){return o(this,e,!0,t)},f.prototype.readUInt16BE=function(e,t){return o(this,e,!1,t)},f.prototype.readUInt32LE=function(e,t){return u(this,e,!0,t)},f.prototype.readUInt32BE=function(e,t){return u(this,e,!1,t)},f.prototype.readInt8=function(e,t){if(t||(d(null!=e,\"missing offset\"),d(e<this.length,\"Trying to read beyond buffer length\")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},f.prototype.readInt16LE=function(e,t){return _(this,e,!0,t)},f.prototype.readInt16BE=function(e,t){return _(this,e,!1,t)},f.prototype.readInt32LE=function(e,t){return E(this,e,!0,t)},f.prototype.readInt32BE=function(e,t){return E(this,e,!1,t)},f.prototype.readFloatLE=function(e,t){return I(this,e,!0,t)},f.prototype.readFloatBE=function(e,t){return I(this,e,!1,t)},f.prototype.readDoubleLE=function(e,t){return A(this,e,!0,t)},f.prototype.readDoubleBE=function(e,t){return A(this,e,!1,t)},f.prototype.writeUInt8=function(e,t,n){n||(d(null!=e,\"missing value\"),d(null!=t,\"missing offset\"),d(t<this.length,\"trying to write beyond buffer length\"),Y(e,255)),t>=this.length||(this[t]=e)},f.prototype.writeUInt16LE=function(e,t,n){s(this,e,t,!0,n)},f.prototype.writeUInt16BE=function(e,t,n){s(this,e,t,!1,n)},f.prototype.writeUInt32LE=function(e,t,n){l(this,e,t,!0,n)},f.prototype.writeUInt32BE=function(e,t,n){l(this,e,t,!1,n)},f.prototype.writeInt8=function(e,t,n){n||(d(null!=e,\"missing value\"),d(null!=t,\"missing offset\"),d(t<this.length,\"Trying to write beyond buffer length\"),F(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},f.prototype.writeInt16LE=function(e,t,n){B(this,e,t,!0,n)},f.prototype.writeInt16BE=function(e,t,n){B(this,e,t,!1,n)},f.prototype.writeInt32LE=function(e,t,n){L(this,e,t,!0,n)},f.prototype.writeInt32BE=function(e,t,n){L(this,e,t,!1,n)},f.prototype.writeFloatLE=function(e,t,n){U(this,e,t,!0,n)},f.prototype.writeFloatBE=function(e,t,n){U(this,e,t,!1,n)},f.prototype.writeDoubleLE=function(e,t,n){x(this,e,t,!0,n)},f.prototype.writeDoubleBE=function(e,t,n){x(this,e,t,!1,n)},f.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,d(\"number\"==typeof(e=\"string\"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),\"value is not a number\"),d(t<=n,\"end < start\"),n!==t&&0!==this.length){d(0<=t&&t<this.length,\"start out of bounds\"),d(0<=n&&n<=this.length,\"end out of bounds\");for(var r=t;r<n;r++)this[r]=e}},f.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=k(this[n]),n===H.INSPECT_MAX_BYTES){e[n+1]=\"...\";break}return\"<Buffer \"+e.join(\" \")+\">\"},f.prototype.toArrayBuffer=function(){if(\"undefined\"==typeof Uint8Array)throw new Error(\"Buffer.toArrayBuffer not supported in this browser\");if(f._useTypedArrays)return new f(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var t=f.prototype;function S(e,t,n){return\"number\"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function j(e){return(e=~~Math.ceil(+e))<0?0:e}function C(e){return(Array.isArray||function(e){return\"[object Array]\"===Object.prototype.toString.call(e)})(e)}function k(e){return e<16?\"0\"+e.toString(16):e.toString(16)}function T(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else for(var o=n,i=(55296<=r&&r<=57343&&n++,encodeURIComponent(e.slice(o,n+1)).substr(1).split(\"%\")),u=0;u<i.length;u++)t.push(parseInt(i[u],16))}return t}function M(e){return a.toByteArray(e)}function c(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function N(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function Y(e,t){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(0<=e,\"specified a negative value for writing an unsigned value\"),d(e<=t,\"value is larger than maximum value for type\"),d(Math.floor(e)===e,\"value has a fractional component\")}function F(e,t,n){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(e<=t,\"value larger than maximum allowed value\"),d(n<=e,\"value smaller than minimum allowed value\"),d(Math.floor(e)===e,\"value has a fractional component\")}function D(e,t,n){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(e<=t,\"value larger than maximum allowed value\"),d(n<=e,\"value smaller than minimum allowed value\")}function d(e,t){if(!e)throw new Error(t||\"Failed assertion\")}f._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=t.get,e.set=t.set,e.write=t.write,e.toString=t.toString,e.toLocaleString=t.toString,e.toJSON=t.toJSON,e.copy=t.copy,e.slice=t.slice,e.readUInt8=t.readUInt8,e.readUInt16LE=t.readUInt16LE,e.readUInt16BE=t.readUInt16BE,e.readUInt32LE=t.readUInt32LE,e.readUInt32BE=t.readUInt32BE,e.readInt8=t.readInt8,e.readInt16LE=t.readInt16LE,e.readInt16BE=t.readInt16BE,e.readInt32LE=t.readInt32LE,e.readInt32BE=t.readInt32BE,e.readFloatLE=t.readFloatLE,e.readFloatBE=t.readFloatBE,e.readDoubleLE=t.readDoubleLE,e.readDoubleBE=t.readDoubleBE,e.writeUInt8=t.writeUInt8,e.writeUInt16LE=t.writeUInt16LE,e.writeUInt16BE=t.writeUInt16BE,e.writeUInt32LE=t.writeUInt32LE,e.writeUInt32BE=t.writeUInt32BE,e.writeInt8=t.writeInt8,e.writeInt16LE=t.writeInt16LE,e.writeInt16BE=t.writeInt16BE,e.writeInt32LE=t.writeInt32LE,e.writeInt32BE=t.writeInt32BE,e.writeFloatLE=t.writeFloatLE,e.writeFloatBE=t.writeFloatBE,e.writeDoubleLE=t.writeDoubleLE,e.writeDoubleBE=t.writeDoubleBE,e.fill=t.fill,e.inspect=t.inspect,e.toArrayBuffer=t.toArrayBuffer,e}}.call(this,O(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},O(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/buffer/index.js\",\"/node_modules/gulp-browserify/node_modules/buffer\")},{\"base64-js\":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(c,d,e){!function(e,t,a,n,r,o,i,u,s){var a=c(\"buffer\").Buffer,f=4,l=new a(f);l.fill(0);d.exports={hash:function(e,t,n,r){for(var o=t(function(e,t){e.length%f!=0&&(n=e.length+(f-e.length%f),e=a.concat([e,l],n));for(var n,r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;i<e.length;i+=f)r.push(o.call(e,i));return r}(e=a.isBuffer(e)?e:new a(e),r),8*e.length),t=r,i=new a(n),u=t?i.writeInt32BE:i.writeInt32LE,s=0;s<o.length;s++)u.call(i,o[s],4*s,!0);return i}}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{buffer:3,lYpoI2:11}],5:[function(v,e,_){!function(l,c,u,d,h,p,g,y,w){var u=v(\"buffer\").Buffer,e=v(\"./sha\"),t=v(\"./sha256\"),n=v(\"./rng\"),b={sha1:e,sha256:t,md5:v(\"./md5\")},s=64,a=new u(s);function r(e,n){var r=b[e=e||\"sha1\"],o=[];return r||i(\"algorithm:\",e,\"is not yet supported\"),{update:function(e){return u.isBuffer(e)||(e=new u(e)),o.push(e),e.length,this},digest:function(e){var t=u.concat(o),t=n?function(e,t,n){u.isBuffer(t)||(t=new u(t)),u.isBuffer(n)||(n=new u(n)),t.length>s?t=e(t):t.length<s&&(t=u.concat([t,a],s));for(var r=new u(s),o=new u(s),i=0;i<s;i++)r[i]=54^t[i],o[i]=92^t[i];return n=e(u.concat([r,n])),e(u.concat([o,n]))}(r,n,t):r(t);return o=null,e?t.toString(e):t}}}function i(){var e=[].slice.call(arguments).join(\" \");throw new Error([e,\"we accept pull requests\",\"http://github.com/dominictarr/crypto-browserify\"].join(\"\\n\"))}a.fill(0),_.createHash=function(e){return r(e)},_.createHmac=r,_.randomBytes=function(e,t){if(!t||!t.call)return new u(n(e));try{t.call(this,void 0,new u(n(e)))}catch(e){t(e)}};var o,f=[\"createCredentials\",\"createCipher\",\"createCipheriv\",\"createDecipher\",\"createDecipheriv\",\"createSign\",\"createVerify\",\"createDiffieHellman\",\"pbkdf2\"],m=function(e){_[e]=function(){i(\"sorry,\",e,\"is not implemented yet\")}};for(o in f)m(f[o],o)}.call(this,v(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},v(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./md5\":6,\"./rng\":7,\"./sha\":8,\"./sha256\":9,buffer:3,lYpoI2:11}],6:[function(w,b,e){!function(e,r,o,i,u,a,f,l,y){var t=w(\"./helpers\");function n(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u<e.length;u+=16){var s=n,a=r,f=o,l=i,n=c(n,r,o,i,e[u+0],7,-680876936),i=c(i,n,r,o,e[u+1],12,-389564586),o=c(o,i,n,r,e[u+2],17,606105819),r=c(r,o,i,n,e[u+3],22,-1044525330);n=c(n,r,o,i,e[u+4],7,-176418897),i=c(i,n,r,o,e[u+5],12,1200080426),o=c(o,i,n,r,e[u+6],17,-1473231341),r=c(r,o,i,n,e[u+7],22,-45705983),n=c(n,r,o,i,e[u+8],7,1770035416),i=c(i,n,r,o,e[u+9],12,-1958414417),o=c(o,i,n,r,e[u+10],17,-42063),r=c(r,o,i,n,e[u+11],22,-1990404162),n=c(n,r,o,i,e[u+12],7,1804603682),i=c(i,n,r,o,e[u+13],12,-40341101),o=c(o,i,n,r,e[u+14],17,-1502002290),n=d(n,r=c(r,o,i,n,e[u+15],22,1236535329),o,i,e[u+1],5,-165796510),i=d(i,n,r,o,e[u+6],9,-1069501632),o=d(o,i,n,r,e[u+11],14,643717713),r=d(r,o,i,n,e[u+0],20,-373897302),n=d(n,r,o,i,e[u+5],5,-701558691),i=d(i,n,r,o,e[u+10],9,38016083),o=d(o,i,n,r,e[u+15],14,-660478335),r=d(r,o,i,n,e[u+4],20,-405537848),n=d(n,r,o,i,e[u+9],5,568446438),i=d(i,n,r,o,e[u+14],9,-1019803690),o=d(o,i,n,r,e[u+3],14,-187363961),r=d(r,o,i,n,e[u+8],20,1163531501),n=d(n,r,o,i,e[u+13],5,-1444681467),i=d(i,n,r,o,e[u+2],9,-51403784),o=d(o,i,n,r,e[u+7],14,1735328473),n=h(n,r=d(r,o,i,n,e[u+12],20,-1926607734),o,i,e[u+5],4,-378558),i=h(i,n,r,o,e[u+8],11,-2022574463),o=h(o,i,n,r,e[u+11],16,1839030562),r=h(r,o,i,n,e[u+14],23,-35309556),n=h(n,r,o,i,e[u+1],4,-1530992060),i=h(i,n,r,o,e[u+4],11,1272893353),o=h(o,i,n,r,e[u+7],16,-155497632),r=h(r,o,i,n,e[u+10],23,-1094730640),n=h(n,r,o,i,e[u+13],4,681279174),i=h(i,n,r,o,e[u+0],11,-358537222),o=h(o,i,n,r,e[u+3],16,-722521979),r=h(r,o,i,n,e[u+6],23,76029189),n=h(n,r,o,i,e[u+9],4,-640364487),i=h(i,n,r,o,e[u+12],11,-421815835),o=h(o,i,n,r,e[u+15],16,530742520),n=p(n,r=h(r,o,i,n,e[u+2],23,-995338651),o,i,e[u+0],6,-198630844),i=p(i,n,r,o,e[u+7],10,1126891415),o=p(o,i,n,r,e[u+14],15,-1416354905),r=p(r,o,i,n,e[u+5],21,-57434055),n=p(n,r,o,i,e[u+12],6,1700485571),i=p(i,n,r,o,e[u+3],10,-1894986606),o=p(o,i,n,r,e[u+10],15,-1051523),r=p(r,o,i,n,e[u+1],21,-2054922799),n=p(n,r,o,i,e[u+8],6,1873313359),i=p(i,n,r,o,e[u+15],10,-30611744),o=p(o,i,n,r,e[u+6],15,-1560198380),r=p(r,o,i,n,e[u+13],21,1309151649),n=p(n,r,o,i,e[u+4],6,-145523070),i=p(i,n,r,o,e[u+11],10,-1120210379),o=p(o,i,n,r,e[u+2],15,718787259),r=p(r,o,i,n,e[u+9],21,-343485551),n=g(n,s),r=g(r,a),o=g(o,f),i=g(i,l)}return Array(n,r,o,i)}function s(e,t,n,r,o,i){return g((t=g(g(t,e),g(r,i)))<<o|t>>>32-o,n)}function c(e,t,n,r,o,i,u){return s(t&n|~t&r,e,t,o,i,u)}function d(e,t,n,r,o,i,u){return s(t&r|n&~r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return s(t^n^r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return s(n^(t|~r),e,t,o,i,u)}function g(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return t.hash(e,n,16)}}.call(this,w(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},w(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],7:[function(e,l,t){!function(e,t,n,r,o,i,u,s,f){var a;l.exports=a||function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{buffer:3,lYpoI2:11}],8:[function(c,d,e){!function(e,t,n,r,o,s,a,f,l){var i=c(\"./helpers\");function u(l,c){l[c>>5]|=128<<24-c%32,l[15+(c+64>>9<<4)]=c;for(var e,t,n,r=Array(80),o=1732584193,i=-271733879,u=-1732584194,s=271733878,d=-1009589776,h=0;h<l.length;h+=16){for(var p=o,g=i,y=u,w=s,b=d,a=0;a<80;a++){r[a]=a<16?l[h+a]:v(r[a-3]^r[a-8]^r[a-14]^r[a-16],1);var f=m(m(v(o,5),(f=i,t=u,n=s,(e=a)<20?f&t|~f&n:!(e<40)&&e<60?f&t|f&n|t&n:f^t^n)),m(m(d,r[a]),(e=a)<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514)),d=s,s=u,u=v(i,30),i=o,o=f}o=m(o,p),i=m(i,g),u=m(u,y),s=m(s,w),d=m(d,b)}return Array(o,i,u,s,d)}function m(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function v(e,t){return e<<t|e>>>32-t}d.exports=function(e){return i.hash(e,u,20,!0)}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],9:[function(c,d,e){!function(e,t,n,r,u,s,a,f,l){function b(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,l){var c,d=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),t=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),n=new Array(64);e[l>>5]|=128<<24-l%32,e[15+(l+64>>9<<4)]=l;for(var r,o,h=0;h<e.length;h+=16){for(var i=t[0],u=t[1],s=t[2],p=t[3],a=t[4],g=t[5],y=t[6],w=t[7],f=0;f<64;f++)n[f]=f<16?e[f+h]:b(b(b((o=n[f-2],m(o,17)^m(o,19)^v(o,10)),n[f-7]),(o=n[f-15],m(o,7)^m(o,18)^v(o,3))),n[f-16]),c=b(b(b(b(w,m(o=a,6)^m(o,11)^m(o,25)),a&g^~a&y),d[f]),n[f]),r=b(m(r=i,2)^m(r,13)^m(r,22),i&u^i&s^u&s),w=y,y=g,g=a,a=b(p,c),p=s,s=u,u=i,i=b(c,r);t[0]=b(i,t[0]),t[1]=b(u,t[1]),t[2]=b(s,t[2]),t[3]=b(p,t[3]),t[4]=b(a,t[4]),t[5]=b(g,t[5]),t[6]=b(y,t[6]),t[7]=b(w,t[7])}return t}var i=c(\"./helpers\"),m=function(e,t){return e>>>t|e<<32-t},v=function(e,t){return e>>>t};d.exports=function(e){return i.hash(e,o,32,!0)}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],10:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){f.read=function(e,t,n,r,o){var i,u,l=8*o-r-1,c=(1<<l)-1,d=c>>1,s=-7,a=n?o-1:0,f=n?-1:1,o=e[t+a];for(a+=f,i=o&(1<<-s)-1,o>>=-s,s+=l;0<s;i=256*i+e[t+a],a+=f,s-=8);for(u=i&(1<<-s)-1,i>>=-s,s+=r;0<s;u=256*u+e[t+a],a+=f,s-=8);if(0===i)i=1-d;else{if(i===c)return u?NaN:1/0*(o?-1:1);u+=Math.pow(2,r),i-=d}return(o?-1:1)*u*Math.pow(2,i-r)},f.write=function(e,t,l,n,r,c){var o,i,u=8*c-r-1,s=(1<<u)-1,a=s>>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:c-1,h=n?1:-1,c=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=s):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+a?d/n:d*Math.pow(2,1-a))*n&&(o++,n/=2),s<=o+a?(i=0,o=s):1<=o+a?(i=(t*n-1)*Math.pow(2,r),o+=a):(i=t*Math.pow(2,a-1)*Math.pow(2,r),o=0));8<=r;e[l+f]=255&i,f+=h,i/=256,r-=8);for(o=o<<r|i,u+=r;0<u;e[l+f]=255&o,f+=h,o/=256,u-=8);e[l+f-h]|=128*c}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/ieee754/index.js\",\"/node_modules/gulp-browserify/node_modules/ieee754\")},{buffer:3,lYpoI2:11}],11:[function(e,h,t){!function(e,t,n,r,o,f,l,c,d){var i,u,s;function a(){}(e=h.exports={}).nextTick=(u=\"undefined\"!=typeof window&&window.setImmediate,s=\"undefined\"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:s?(i=[],window.addEventListener(\"message\",function(e){var t=e.source;t!==window&&null!==t||\"process-tick\"!==e.data||(e.stopPropagation(),0<i.length&&i.shift()())},!0),function(e){i.push(e),window.postMessage(\"process-tick\",\"*\")}):function(e){setTimeout(e,0)}),e.title=\"browser\",e.browser=!0,e.env={},e.argv=[],e.on=a,e.addListener=a,e.once=a,e.off=a,e.removeListener=a,e.removeAllListeners=a,e.emit=a,e.binding=function(e){throw new Error(\"process.binding is not supported\")},e.cwd=function(){return\"/\"},e.chdir=function(e){throw new Error(\"process.chdir is not supported\")}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/process/browser.js\",\"/node_modules/gulp-browserify/node_modules/process\")},{buffer:3,lYpoI2:11}]},{},[1])(1)});","import hash from \"object-hash\";\nimport { GeoPoint } from \"@rebasepro/types\";\n\n/** @private is the value an empty array? */\nexport const isEmptyArray = (value?: unknown) =>\n Array.isArray(value) && value.length === 0;\n\n/** @private is the given object a Function? */\nexport const isFunction = (obj: unknown): obj is (...args: unknown[]) => unknown =>\n typeof obj === \"function\";\n\n/** @private is the given object an integer? */\nexport const isInteger = (obj: unknown): boolean =>\n String(Math.floor(Number(obj))) === String(obj);\n\n/** @private is the given object a NaN? */\n\nexport const isNaN = (obj: unknown): boolean => obj !== obj;\n\n/**\n * Deeply get a value from an object via its path.\n */\nexport function getIn(\n obj: Record<string, unknown> | unknown[] | unknown,\n key: string | string[],\n def?: unknown,\n p = 0\n) {\n const path = toPath(key);\n while (obj && p < path.length) {\n obj = (obj as Record<string, unknown>)[path[p++]];\n }\n\n // check if path is not in the end\n if (p !== path.length && !obj) {\n return def;\n }\n\n return obj === undefined ? def : obj;\n}\n\nexport function setIn<T>(obj: T, path: string, value: unknown): T {\n const res = clone(obj) as Record<string, unknown>;\n let resVal: Record<string, unknown> = res;\n let i = 0;\n const pathArray = toPath(path);\n\n for (; i < pathArray.length - 1; i++) {\n const currentPath: string = pathArray[i];\n const currentObj = getIn(obj as Record<string, unknown>, pathArray.slice(0, i + 1));\n\n if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {\n resVal = resVal[currentPath] = clone(currentObj) as Record<string, unknown>;\n } else {\n const nextPath: string = pathArray[i + 1];\n resVal = resVal[currentPath] =\n (isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}) as Record<string, unknown>;\n }\n }\n\n // Return original object if new value is the same as current\n if ((i === 0 ? obj as Record<string, unknown> : resVal)[pathArray[i]] === value) {\n return obj;\n }\n\n if (value === undefined) {\n delete resVal[pathArray[i]];\n } else {\n resVal[pathArray[i]] = value;\n }\n\n // If the path array has a single element, the loop did not run.\n // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.\n if (i === 0 && value === undefined) {\n delete res[pathArray[i]];\n }\n\n return res as T;\n}\n\nexport function clone<T>(value: T): T {\n if (Array.isArray(value)) {\n return [...value] as T;\n } else if (typeof value === \"object\" && value !== null) {\n return { ...value } as T;\n } else {\n return value; // This is for primitive types which do not need cloning.\n }\n}\n\n/**\n * Deep clone a value, preserving function references and class instances.\n * Unlike structuredClone, this handles objects that contain functions\n * (e.g. CollectionConfig with target(), childCollections(), callbacks).\n */\nexport function deepClone<T>(value: T): T {\n if (value === null || value === undefined) return value;\n if (typeof value === \"function\") return value;\n if (typeof value !== \"object\") return value;\n\n if (Array.isArray(value)) {\n return value.map(item => deepClone(item)) as T;\n }\n\n // Preserve class instances (Date, GeoPoint, etc.) — don't recurse\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return value;\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = deepClone((value as Record<string, unknown>)[key]);\n }\n return result as T;\n}\n\nfunction toPath(value: string | string[]) {\n if (Array.isArray(value)) return value; // Already in path array form.\n // Replace brackets with dots, remove leading/trailing dots, then split by dot.\n return value.replace(/\\[(\\d+)]/g, \".$1\").replace(/^\\./, \"\").replace(/\\.$/, \"\").split(\".\");\n}\n\n\nexport const pick: <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => Partial<T> = <T extends Record<string, unknown>>(obj: T, ...args: (keyof T)[]) => ({\n ...args.reduce<Record<string, unknown>>((res, key) => ({\n ...res,\n [key as string]: obj[key as string]\n }), {})\n}) as Partial<T>;\n\nexport function isObject(item: unknown): item is Record<string, unknown> {\n return !!item && typeof item === \"object\" && !Array.isArray(item);\n}\n\nexport function isPlainObject(obj: unknown): obj is Record<string, unknown> {\n // 1. Rule out non-objects, null, and arrays\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) {\n return false;\n }\n\n // 2. Get the object's direct prototype\n const proto = Object.getPrototypeOf(obj);\n\n // 3. A plain object's direct prototype is Object.prototype\n return proto === Object.prototype;\n}\n\nexport function mergeDeep<T extends object, U extends object>(\n target: T,\n source: U,\n ignoreUndefined = false\n): T & U {\n // If target is not a true object (e.g., null, array, primitive), return target itself.\n if (!isObject(target)) {\n return target as T & U;\n }\n\n // Create a shallow copy of the target to avoid modifying the original object.\n const output = { ...target };\n\n // If source is not a true object, there's nothing to merge from it.\n // Return the shallow copy of target.\n if (!isObject(source)) {\n return output as T & U;\n }\n\n // Iterate over keys in the source object.\n for (const key in source) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n continue;\n }\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const outputValue = (output as Record<string, unknown>)[key]; // Current value in our merged object (originating from target)\n\n // Skip if source value is undefined and ignoreUndefined is true.\n // This handles both not adding new undefined properties and not overwriting existing properties with undefined.\n if (ignoreUndefined && sourceValue === undefined) {\n continue;\n }\n\n if (sourceValue instanceof Date) {\n // If source value is a Date, create a new Date instance.\n (output as Record<string, unknown>)[key] = new Date(sourceValue.getTime());\n } else if (Array.isArray(sourceValue)) {\n if (Array.isArray(outputValue)) {\n // If the array contains primitives or class instances (non-plain objects),\n // overwrite the array entirely instead of doing element-wise merging.\n const hasPlainObjects = sourceValue.some(isPlainObject) || outputValue.some(isPlainObject);\n if (!hasPlainObjects) {\n (output as Record<string, unknown>)[key] = [...sourceValue];\n } else {\n const newArray = [];\n const maxLength = Math.max(outputValue.length, sourceValue.length);\n for (let i = 0; i < maxLength; i++) {\n const sourceItem = sourceValue[i];\n const targetItem = outputValue[i];\n\n if (i >= sourceValue.length) { // source is shorter\n newArray[i] = targetItem;\n } else if (i >= outputValue.length) { // target is shorter\n newArray[i] = sourceItem;\n } else if (sourceItem === null) {\n newArray[i] = targetItem;\n } else if (isPlainObject(sourceItem) && isPlainObject(targetItem)) {\n // Only recursively merge plain objects, preserve class instances\n newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);\n } else {\n // For class instances and primitives, use source directly\n newArray[i] = sourceItem;\n }\n }\n (output as Record<string, unknown>)[key] = newArray;\n }\n } else {\n // If output's value (from target) is not an array,\n // overwrite with a shallow copy of the source array.\n (output as Record<string, unknown>)[key] = [...sourceValue];\n }\n } else if (isPlainObject(sourceValue)) {\n // If source value is a plain object (not a class instance like EntityReference, GeoPoint, etc.):\n if (isPlainObject(outputValue)) {\n // If the corresponding value in output (from target) is also a plain object, recurse.\n // Ensure the ignoreUndefined flag is passed down.\n (output as Record<string, unknown>)[key] = mergeDeep(outputValue as Record<string, unknown>, sourceValue, ignoreUndefined);\n } else {\n // If output's value (from target) is not a plain object (e.g., null, primitive, class instance, or key didn't exist in original target),\n // overwrite with the source object.\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n } else if (isObject(sourceValue)) {\n // If source value is a class instance (not a plain object), use it directly to preserve prototype\n (output as Record<string, unknown>)[key] = sourceValue;\n } else {\n // If source value is a primitive, null, or undefined (and not ignored).\n (output as Record<string, unknown>)[key] = sourceValue;\n }\n }\n }\n\n return output as T & U;\n}\n\nexport function getValueInPath(o: object | undefined, path: string): unknown {\n if (!o) return undefined;\n if (typeof o === \"object\") {\n if (path in o) {\n return (o as Record<string, unknown>)[path];\n }\n if (path.includes(\".\") || path.includes(\"[\")) {\n let pathSegments = path.split(/[.[]/);\n if (path.includes(\"[\")) {\n pathSegments = pathSegments.map(segment => segment.replace(\"]\", \"\"));\n }\n const firstSegment = pathSegments[0];\n const isArrayAndIndexExists = Array.isArray((o as Record<string, unknown>)[firstSegment]) && !isNaN(parseInt(pathSegments[1]));\n const nextObject = isArrayAndIndexExists\n ? ((o as Record<string, unknown>)[firstSegment] as unknown[])[parseInt(pathSegments[1])]\n : (o as Record<string, unknown>)[firstSegment];\n\n const nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(\".\");\n if (nextPath === \"\")\n return nextObject;\n return getValueInPath(nextObject as object | undefined, nextPath);\n }\n }\n return undefined;\n}\n\nexport function removeInPath(o: object, path: string): object | undefined {\n const res = clone(o) as Record<string, unknown>;\n let current = res;\n const parts = path.split(\".\");\n const last = parts.pop();\n for (const part of parts) {\n if (part in current && current[part] !== null && typeof current[part] === \"object\") {\n current[part] = clone(current[part]) as Record<string, unknown>;\n current = current[part] as Record<string, unknown>;\n } else {\n return res;\n }\n }\n if (last && current && typeof current === \"object\") {\n delete current[last];\n }\n return res;\n}\n\nexport function removeFunctions(o: unknown): unknown {\n if (o === undefined) return undefined;\n if (o === null) return null;\n if (typeof o === \"object\") {\n // Handle arrays first - map over them recursively\n if (Array.isArray(o)) {\n return o.map(v => removeFunctions(v));\n }\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(o)) {\n return o;\n }\n return Object.entries(o)\n .filter(([_, value]) => typeof value !== \"function\")\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return { [key]: value.map(v => removeFunctions(v)) };\n } else if (typeof value === \"object\") {\n return { [key]: removeFunctions(value) };\n } else return { [key]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n }\n return o;\n}\n\nexport function getHashValue<T>(v: T): string | null {\n if (!v) return null;\n if (typeof v === \"object\" && v !== null) {\n if (\"id\" in v)\n return String((v as Record<string, unknown>).id);\n else if (v instanceof Date)\n return v.toLocaleString();\n else if (v instanceof GeoPoint)\n return hash(v as Record<string, unknown>);\n }\n return hash(v as object, { ignoreUnknown: true });\n}\n\nexport function removeUndefined(value: unknown, removeEmptyStrings?: boolean): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeUndefined(v, removeEmptyStrings));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n Object.keys(value).forEach((key) => {\n if (!isEmptyObject(value as object)) {\n const childRes = removeUndefined((value as Record<string, unknown>)[key], removeEmptyStrings);\n const isString = typeof childRes === \"string\";\n const shouldKeepIfString = !removeEmptyStrings || (removeEmptyStrings && !isString) || (removeEmptyStrings && isString && childRes !== \"\");\n if (childRes !== undefined && !isEmptyObject(childRes as object) && shouldKeepIfString)\n res[key] = childRes;\n }\n });\n return res;\n }\n return value;\n}\n\nexport function removeNulls(value: unknown): unknown {\n if (typeof value === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v: unknown) => removeNulls(v));\n }\n if (typeof value === \"object\") {\n if (value === null)\n return value;\n // Preserve class instances (EntityReference, GeoPoint, etc.) - don't recurse into them\n if (!isPlainObject(value)) {\n return value;\n }\n const res: Record<string, unknown> = {};\n const obj = value as Record<string, unknown>;\n Object.keys(obj).forEach((key) => {\n if (obj[key] !== null)\n res[key] = removeNulls(obj[key]);\n });\n return res;\n }\n return value;\n}\n\nexport function isEmptyObject(obj: object) {\n return obj &&\n Object.getPrototypeOf(obj) === Object.prototype &&\n Object.keys(obj).length === 0\n}\n\nexport function removePropsIfExisting(source: Record<string, unknown> | unknown[], comparison: Record<string, unknown> | unknown[]) {\n const isObject = (val: unknown): val is Record<string, unknown> => typeof val === \"object\" && val !== null;\n const isArray = (val: unknown): val is unknown[] => Array.isArray(val);\n\n if (!isObject(source) || !isObject(comparison)) {\n return source;\n }\n\n const res = isArray(source) ? [...source] : { ...source };\n\n if (isArray(res)) {\n for (let i = res.length - 1; i >= 0; i--) {\n if (res[i] === comparison[i]) {\n res.splice(i, 1);\n } else if (isObject(res[i]) && isObject(comparison[i])) {\n res[i] = removePropsIfExisting(res[i] as unknown as Record<string, unknown>, (comparison as unknown as unknown[])[i] as Record<string, unknown>);\n }\n }\n } else {\n Object.keys(comparison).forEach(key => {\n if (key in res) {\n if (isObject(res[key]) && isObject(comparison[key])) {\n res[key] = removePropsIfExisting(res[key], comparison[key]);\n } else if (res[key] === comparison[key]) {\n delete res[key];\n }\n }\n });\n }\n\n return res;\n}\n","/**\n * Minimal SHA-1 implementation that runs in both Node and the browser.\n *\n * This exists because generated Postgres policy names embed a SHA-1 digest of\n * the security rule. The DDL generator runs on the server (where `node:crypto`\n * is available) but the Studio has to derive the same names in the browser to\n * tell a policy it generated apart from one it did not. `node:crypto` cannot be\n * bundled for the browser, so the shared derivation needs a portable digest.\n *\n * SHA-1 is used purely to name things deterministically — never for security.\n * The output is byte-identical to `createHash(\"sha1\").update(str).digest(\"hex\")`,\n * which `sha1.test.ts` pins against `node:crypto` directly.\n */\n\n/** Rotate a 32-bit word left by `n` bits. */\nfunction rotl(value: number, n: number): number {\n return (value << n) | (value >>> (32 - n));\n}\n\n/**\n * SHA-1 digest of a string, hex-encoded.\n *\n * The input is encoded as UTF-8, matching Node's default handling of strings\n * passed to `hash.update(str)`.\n */\nexport function sha1Hex(input: string): string {\n const bytes: number[] = Array.from(new TextEncoder().encode(input));\n const bitLength = bytes.length * 8;\n\n // Padding: 0x80, then zeroes up to 56 bytes mod 64, then the length as a\n // 64-bit big-endian integer.\n bytes.push(0x80);\n while (bytes.length % 64 !== 56) bytes.push(0);\n\n const hi = Math.floor(bitLength / 0x100000000);\n const lo = bitLength >>> 0;\n bytes.push((hi >>> 24) & 0xff, (hi >>> 16) & 0xff, (hi >>> 8) & 0xff, hi & 0xff);\n bytes.push((lo >>> 24) & 0xff, (lo >>> 16) & 0xff, (lo >>> 8) & 0xff, lo & 0xff);\n\n let h0 = 0x67452301;\n let h1 = 0xefcdab89;\n let h2 = 0x98badcfe;\n let h3 = 0x10325476;\n let h4 = 0xc3d2e1f0;\n\n const w = new Array<number>(80);\n\n for (let offset = 0; offset < bytes.length; offset += 64) {\n for (let i = 0; i < 16; i++) {\n const j = offset + i * 4;\n w[i] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) | 0;\n }\n for (let i = 16; i < 80; i++) {\n w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n\n for (let i = 0; i < 80; i++) {\n let f: number;\n let k: number;\n if (i < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (i < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (i < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n\n const temp = (rotl(a, 5) + f + e + k + w[i]) | 0;\n e = d;\n d = c;\n c = rotl(b, 30);\n b = a;\n a = temp;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n }\n\n return [h0, h1, h2, h3, h4]\n .map(word => (word >>> 0).toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n","import type { SecurityOperation, SecurityRule } from \"@rebasepro/types\";\nimport { sha1Hex } from \"./sha1\";\n\n/**\n * Naming of the Postgres policies generated from a collection's security rules.\n *\n * A rule without an explicit `name` is compiled to `<table>_<op>_<hash>`, where\n * the hash covers the rule's semantics. The Studio needs the same names to tell\n * \"this policy came from your code\" apart from \"someone wrote this in SQL\" —\n * without them it treats generated policies as foreign and offers to import\n * them back into the codebase they came from.\n *\n * This is the single definition of that naming. The DDL and Drizzle generators\n * both derive names from here, so a change cannot silently rename every policy\n * in every deployed database while the UI keeps matching the old ones.\n */\n\n/** Stable digest of the parts of a rule that determine what the policy does. */\nexport function getPolicyNameHash(rule: SecurityRule): string {\n const data = JSON.stringify({\n a: rule.access,\n m: rule.mode,\n op: rule.operation,\n ops: rule.operations?.slice().sort(),\n own: rule.ownerField,\n rol: rule.roles?.slice().sort(),\n pg: rule.pgRoles?.slice().sort(),\n u: rule.using,\n w: rule.withCheck,\n c: rule.condition,\n ch: rule.check\n });\n return sha1Hex(data).substring(0, 7);\n}\n\n/** The operations a rule expands to — `operations` wins over `operation`. */\nexport function getPolicyOperations(rule: SecurityRule): readonly SecurityOperation[] {\n return rule.operations && rule.operations.length > 0\n ? rule.operations\n : [rule.operation ?? \"all\"];\n}\n\n/**\n * Every Postgres policy name a single rule compiles to — one per operation.\n *\n * @param rule The security rule as written in the collection config.\n * @param tableName The rule's table (see `getTableName` in `@rebasepro/common`).\n */\nexport function getPolicyNamesForRule(rule: SecurityRule, tableName: string): string[] {\n const ops = getPolicyOperations(rule);\n const ruleHash = getPolicyNameHash(rule);\n\n return ops.map((op, opIdx) => rule.name\n ? (ops.length > 1 ? `${rule.name}_${op}` : rule.name)\n : `${tableName}_${op}_${ruleHash}${ops.length > 1 ? `_${opIdx}` : \"\"}`);\n}\n\n/** Every policy name a set of rules compiles to, for membership checks. */\nexport function getPolicyNamesForRules(rules: SecurityRule[], tableName: string): Set<string> {\n const names = new Set<string>();\n for (const rule of rules) {\n for (const name of getPolicyNamesForRule(rule, tableName)) names.add(name);\n }\n return names;\n}\n","import { toSnakeCase } from \"./strings\";\n\n/**\n * Generates a foreign key column name from a given string, typically a collection slug or name.\n * It converts the name to snake_case, attempts to singularize it by removing a trailing 's'\n * (a common convention for collection names), and appends '_id'.\n *\n * @param name The base name to convert to a foreign key.\n * @returns A foreign key name in the format 'singular_name_id'.\n *\n * @example\n * // returns \"user_id\"\n * generateForeignKeyName(\"users\")\n *\n * @example\n * // returns \"post_id\"\n * generateForeignKeyName(\"posts\")\n *\n * @example\n * // returns \"product_id\"\n * generateForeignKeyName(\"Product\")\n *\n */\nexport function generateForeignKeyName(name: string): string {\n const snakeCaseName = toSnakeCase(name);\n // A simple heuristic to singularize a plural name, which is a common convention.\n const singularName = snakeCaseName.endsWith(\"s\") ? snakeCaseName.slice(0, -1) : snakeCaseName;\n return `${singularName}_id`;\n}\n\n","import {\n DataType,\n Entity,\n EntityReference,\n EntityRelation,\n EntityStatus,\n EntityValues,\n Properties,\n Property\n} from \"@rebasepro/types\";\nimport { DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE } from \"./common\";\nimport { mergeDeep } from \"@rebasepro/utils\";\n\nexport function isPropertyBuilder(property?: Property) {\n return typeof property?.dynamicProps === \"function\";\n}\n\nexport function getDefaultValuesFor<M extends Record<string, unknown>>(properties: Properties): Partial<EntityValues<M>> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (!property) return {};\n const value = getDefaultValueFor(property);\n return value === undefined ? {} : { [key]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {}) as EntityValues<M>;\n}\n\nexport function getDefaultValueFor(property?: Property): unknown {\n if (!property) return undefined;\n if (isPropertyBuilder(property)) return undefined;\n if (property.defaultValue || property.defaultValue === null) {\n return property.defaultValue;\n } else if (property.type === \"map\" && property.properties) {\n const defaultValuesFor = getDefaultValuesFor(property.properties as Properties);\n if (Object.keys(defaultValuesFor).length === 0) return undefined;\n return defaultValuesFor;\n } else {\n return getDefaultValueFortype(property.type);\n }\n}\n\nexport function getDefaultValueFortype(type: DataType): unknown {\n if (type === \"string\") {\n return null;\n } else if (type === \"number\") {\n return null;\n } else if (type === \"boolean\") {\n return false;\n } else if (type === \"date\") {\n return null;\n } else if (type === \"array\") {\n return [];\n } else if (type === \"map\") {\n return {};\n } else if (type === \"vector\") {\n return null;\n } else if (type === \"binary\") {\n return null;\n } else {\n return null;\n }\n}\n\n/**\n * Update the automatic values in a entity before save\n * @group Driver\n */\nexport function updateDateAutoValues<M extends Record<string, unknown>>({\n inputValues,\n properties,\n status,\n timestampNowValue\n}:\n {\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n status: EntityStatus,\n timestampNowValue: unknown\n }): EntityValues<M> {\n return traverseValuesProperties(\n inputValues,\n properties,\n (inputValue, property) => {\n if (property.type === \"date\") {\n if (status === \"existing\" && property.autoValue === \"on_update\") {\n return timestampNowValue;\n } else if ((status === \"new\" || status === \"copy\") &&\n (property.autoValue === \"on_update\" || property.autoValue === \"on_create\")) {\n return timestampNowValue;\n } else {\n return inputValue;\n }\n } else {\n return inputValue;\n }\n }\n ) ?? {} as M;\n}\n\n/**\n * Add missing required fields, expected in the collection, to the values of a entity\n * @param values\n * @param properties\n * @group Driver\n */\nexport function sanitizeData<M extends Record<string, unknown>>\n (\n values: EntityValues<M>,\n properties: Properties\n ) {\n const result = values as Record<string, unknown>;\n Object.entries(properties)\n .forEach(([key, property]) => {\n if (values && values[key] !== undefined) result[key] = values[key];\n else if ((property as Property).validation?.required) result[key] = null;\n });\n return result;\n}\n\nexport function getReferenceFrom<M extends Record<string, unknown>>(entity: Entity<M>): EntityReference {\n if (typeof entity.id !== \"string\")\n throw new Error(\"Only string IDs are supported in references\");\n return new EntityReference({\n id: entity.id,\n path: entity.path,\n driver: entity.driver,\n databaseId: entity.databaseId\n });\n}\n\nexport function getRelationFrom<M extends Record<string, unknown>>(entity: Entity<M>): EntityRelation {\n return new EntityRelation(entity.id, entity.path, entity as unknown as Record<string, unknown>);\n}\n\n/**\n * Normalize a value into a proper EntityRelation instance.\n * Handles EntityRelation class instances, and plain objects\n * with `__type === \"relation\"` or an `isEntityRelation()` method.\n *\n * When `propertyType` is `\"relation\"`, also accepts plain objects that\n * have `id` and `path` fields — these are relation-shaped objects from\n * edge cases in the data pipeline (REST fallback, stale cache, custom data source).\n *\n * Returns null if the value cannot be coerced.\n */\nexport function normalizeToEntityRelation(value: unknown, propertyType?: string): EntityRelation | null {\n if (value instanceof EntityRelation) return value;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\n const obj = value as Record<string, unknown>;\n const isRelationLike =\n obj.__type === \"relation\" ||\n obj.__type === \"reference\" ||\n (typeof obj.isEntityRelation === \"function\" && (obj.isEntityRelation as () => boolean)()) ||\n (typeof obj.isEntityReference === \"function\" && (obj.isEntityReference as () => boolean)()) ||\n (propertyType === \"relation\" && typeof obj.id !== \"undefined\" && typeof obj.path === \"string\");\n\n if (!isRelationLike) return null;\n\n return new EntityRelation(\n obj.id as string | number,\n obj.path as string,\n obj.data as Record<string, unknown> | undefined\n );\n}\n\nexport function traverseValuesProperties<M extends Record<string, unknown>>(\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n operation: (value: unknown, property: Property) => unknown\n): EntityValues<M> | undefined {\n // Handle null/undefined inputValues - use empty object as base for mergeDeep\n const safeInputValues = inputValues ?? {};\n\n const updatedValues = Object.entries(properties)\n .map(([key, property]) => {\n const inputValue = safeInputValues && (safeInputValues)[key];\n const updatedValue = traverseValueProperty(inputValue, property as Property, operation);\n if (updatedValue === null) return null;\n if (updatedValue === undefined) return undefined;\n return ({ [key]: updatedValue });\n })\n .reduce((a, b) => ({ ...a,\n...b }), {}) as EntityValues<M>;\n // Use mergeDeep to preserve class instances like EntityReference, GeoPoint\n const result = mergeDeep(safeInputValues, updatedValues);\n if (!result || Object.keys(result).length === 0) return undefined;\n return result;\n}\n\nexport function traverseValueProperty(inputValue: unknown,\n property: Property,\n operation: (value: unknown, property: Property) => unknown): unknown {\n\n let value;\n if (property.type === \"map\" && property.properties) {\n value = traverseValuesProperties(inputValue as Partial<Record<string, unknown>>, property.properties, operation);\n } else if (property.type === \"array\") {\n const of = property.of;\n if (of && Array.isArray(inputValue) && !Array.isArray(of)) {\n value = inputValue.map((e) => traverseValueProperty(e, of, operation));\n } else if (of && Array.isArray(inputValue) && Array.isArray(of)) {\n value = inputValue.map((e, i) => {\n if (i < of.length)\n return traverseValueProperty(e, of[i], operation);\n return null\n }).filter(Boolean);\n } else if (property.oneOf && Array.isArray(inputValue)) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const valueField = property.oneOf?.valueField ?? DEFAULT_ONE_OF_VALUE;\n value = inputValue.map((e) => {\n if (e === null) return null;\n if (typeof e !== \"object\") return e;\n const rec = e as Record<string, unknown>;\n const type = rec[typeField] as string;\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return e;\n return {\n [typeField]: type,\n [valueField]: traverseValueProperty(rec[valueField], childProperty, operation)\n };\n });\n } else {\n value = inputValue;\n }\n } else {\n value = operation(inputValue, property);\n }\n\n return value;\n}\n\n/**\n * Relation reference types used throughout the server layer.\n * These replace the 50+ manual `{ id, path, __type: \"relation\" }` constructions.\n */\nexport interface RelationRef {\n readonly id: string | number;\n readonly path: string;\n readonly __type: \"relation\";\n}\n\nexport interface RelationRefWithData extends RelationRef {\n readonly data: Entity;\n}\n\n/**\n * Create a lightweight relation stub for CMS views.\n * Replaces inline `{ id, path, __type: \"relation\" }` object literals.\n */\nexport function createRelationRef(id: string | number, path: string): RelationRef {\n return { id,\npath,\n__type: \"relation\" };\n}\n\n/**\n * Create a hydrated relation reference that includes the full entity data.\n * Used when entity data has been pre-fetched (e.g., via batch loading or JOINs).\n */\nexport function createRelationRefWithData(id: string | number, path: string, data: Entity): RelationRefWithData {\n return { id,\npath,\n__type: \"relation\",\ndata };\n}\n","/**\n * Row identity: the address of a row, and how to derive it.\n *\n * Postgres has no `id`. A row is identified by its primary key — one or more\n * columns, with any names and any types. `id` is something we synthesize on top\n * of that: a single string token, because the admin needs *one* value it can put\n * in a URL (`/products/1:::2`), use as a cache key, and hang a relation ref off.\n *\n * That token is an address, not data. It is derived from the row's columns and\n * never stored in them — a row is exactly its columns, with their real types.\n * Writing the address back into the row is what used to rename primary keys\n * (`sku` → `id`) and restringify them (`42` → `\"42\"`) on the way out.\n *\n * These live in `common` because both sides need them and must agree exactly:\n * the driver parses an incoming address back into key columns, and the admin\n * derives the address from a row it was served.\n */\n\n/**\n * A primary-key column: its name, the type it round-trips as, and whether it is\n * a UUID (which is a string despite sometimes being described as an id \"number\").\n */\nexport interface PrimaryKeyInfo {\n fieldName: string;\n type: \"string\" | \"number\";\n isUUID?: boolean;\n}\n\n/** Separator between the parts of a composite address. */\nexport const COMPOSITE_ID_SEPARATOR = \":::\";\n\n/**\n * Derive a row's address from its key columns.\n *\n * Single key → the value as a string. Composite → each part joined by\n * {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what\n * {@link parseIdValues} expects to invert.\n */\nexport function buildCompositeId(values: Record<string, unknown>, primaryKeys: PrimaryKeyInfo[]): string {\n if (primaryKeys.length === 0) {\n return \"\";\n }\n if (primaryKeys.length === 1) {\n return String(values[primaryKeys[0].fieldName] ?? \"\");\n }\n return primaryKeys.map(pk => String(values[pk.fieldName] ?? \"\")).join(COMPOSITE_ID_SEPARATOR);\n}\n\n/**\n * Invert {@link buildCompositeId}: turn an address back into key columns, each\n * coerced to the type its column actually round-trips as.\n *\n * This is the boundary where a URL segment becomes a query parameter, so a\n * malformed address must throw rather than silently produce a query that\n * matches the wrong row (or none).\n */\nexport function parseIdValues(idValue: string | number, primaryKeys: PrimaryKeyInfo[]): Record<string, string | number> {\n const result: Record<string, string | number> = {};\n\n if (primaryKeys.length === 0) {\n return result;\n }\n\n if (primaryKeys.length === 1) {\n const pk = primaryKeys[0];\n if (pk.type === \"number\" && !pk.isUUID) {\n const parsed = typeof idValue === \"number\" ? idValue : parseInt(String(idValue), 10);\n if (isNaN(parsed)) {\n throw new Error(`Invalid numeric ID: ${idValue}`);\n }\n result[pk.fieldName] = parsed;\n } else {\n result[pk.fieldName] = String(idValue);\n }\n return result;\n }\n\n // Composite key\n const parts = String(idValue).split(COMPOSITE_ID_SEPARATOR);\n if (parts.length !== primaryKeys.length) {\n throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);\n }\n\n for (let i = 0; i < primaryKeys.length; i++) {\n const pk = primaryKeys[i];\n const val = parts[i];\n if (pk.type === \"number\" && !pk.isUUID) {\n const parsed = parseInt(val, 10);\n if (isNaN(parsed)) {\n throw new Error(`Invalid numeric ID component: ${val}`);\n }\n result[pk.fieldName] = parsed;\n } else {\n result[pk.fieldName] = val;\n }\n }\n\n return result;\n}\n\n/**\n * The primary keys of a collection, as declared by its properties.\n *\n * This is the only tier both sides can read, because it is the only one written\n * in the config: the postgres driver can also infer keys from the Drizzle\n * schema, which the browser never sees and is never sent — the admin compiles\n * the collection files into its own bundle rather than being served them. A key\n * that lives only in the Drizzle schema is therefore invisible here, and the\n * server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`\n * to add.\n *\n * Returns an empty array when a collection declares none, which callers must\n * treat as \"not addressable\" rather than defaulting to `id`: guessing a key\n * that is not the real one produces confidently wrong addresses.\n */\nexport function getDeclaredPrimaryKeys(collection: {\n properties?: Record<string, unknown>;\n}): PrimaryKeyInfo[] {\n const properties = collection.properties;\n if (!properties) return [];\n\n const keys: PrimaryKeyInfo[] = [];\n for (const [fieldName, propRaw] of Object.entries(properties)) {\n const prop = propRaw as { type?: string; isId?: unknown } | undefined;\n if (!prop || typeof prop !== \"object\") continue;\n if (!(\"isId\" in prop) || !prop.isId) continue;\n keys.push({\n fieldName,\n type: prop.type === \"number\" ? \"number\" : \"string\",\n isUUID: prop.isId === \"uuid\"\n });\n }\n return keys;\n}\n\n/**\n * The keys to address a collection's rows with, resolved the way the driver\n * resolves them — minus the tier the browser cannot reach.\n *\n * The postgres driver tries, in order: properties marked `isId`; the primary\n * keys of the Drizzle schema; and finally a column literally named `id`. Only\n * the first and last are visible in a `CollectionConfig`, which is what both\n * sides share.\n *\n * So the two agree except on a collection that declares no `isId` and whose key\n * is known only to Drizzle. There, the driver reads the real key, and this\n * either resolves nothing (reported to the console by the caller) or — if the\n * table happens to have an unrelated `id` property — resolves `id`, which is\n * the wrong key and cannot be detected from here: the addresses look right and\n * route wrong. Only the config can settle it, so the server names both cases\n * at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.\n */\nexport function resolvePrimaryKeys(collection: {\n properties?: Record<string, unknown>;\n}): PrimaryKeyInfo[] {\n const declared = getDeclaredPrimaryKeys(collection);\n if (declared.length > 0) return declared;\n\n const idProp = collection.properties?.id as { type?: string } | undefined;\n if (idProp && typeof idProp === \"object\") {\n return [{ fieldName: \"id\",\ntype: idProp.type === \"number\" ? \"number\" : \"string\" }];\n }\n\n return [];\n}\n","import { EnumValueConfig, EnumValues } from \"@rebasepro/types\";\n\nexport function enumToObjectEntries(enumValues: EnumValues): EnumValueConfig[] {\n if (Array.isArray(enumValues)) {\n return enumValues;\n } else {\n return Object.entries(enumValues).map(([id, value]) => {\n if (typeof value === \"string\") {\n return {\n id,\n label: value\n }\n } else {\n return {\n ...value,\n id\n }\n }\n });\n }\n}\n\nexport function getLabelOrConfigFrom(enumValues: EnumValueConfig[], key?: string | number): EnumValueConfig | undefined {\n if (key === null || key === undefined) return undefined;\n return enumValues.find((entry) => String(entry.id) === String(key));\n}\n","import {\n CollectionConfig,\n Relation,\n ResolvedRelation\n} from \"@rebasepro/types\";\nimport { generateForeignKeyName, toSnakeCase } from \"@rebasepro/utils\";\n\nimport { getTableName } from \"./relations\";\n\n/**\n * Fill in a relation's defaults.\n *\n * This replaces `sanitizeRelation`, which had to work out *which kind of link\n * you meant* from whichever optional fields happened to be set — 194 lines of\n * it, including a pass that inspected the target collection's own relations to\n * decide whether a `many`/`inverse` pair was a one-to-many or the far side of a\n * many-to-many, wrapped in a `try/catch` that fell through to the wrong answer\n * when it could not tell. Two consumers running that logic at different moments\n * could reach different conclusions about the same relation.\n *\n * With the kind declared there is nothing to work out. What remains is\n * defaulting — a table name, a column name — which is deterministic, depends\n * only on the relation and its two endpoints, and cannot fail. That is why this\n * function returns rather than throws, and why it needs no cache to be\n * consistent.\n */\nexport function resolveRelation(\n relation: Relation,\n sourceCollection: CollectionConfig,\n propertyKey?: string\n): ResolvedRelation {\n const target = relation.target;\n if (typeof target !== \"function\") {\n throw new Error(\n `Relation${relation.relationName ? ` '${relation.relationName}'` : \"\"} on ` +\n `'${sourceCollection.slug}' has no \\`target\\`. Give it a thunk: \\`target: () => otherCollection\\`.`\n );\n }\n\n const targetCollection = target();\n if (!targetCollection?.slug) {\n throw new Error(\n `Relation${relation.relationName ? ` '${relation.relationName}'` : \"\"} on ` +\n `'${sourceCollection.slug}' has a \\`target\\` that did not resolve to a collection.`\n );\n }\n\n // The name is the address: the `include` key, the admin tab, and the\n // segment of a nested path. Declared name wins, then the declaring\n // property's key, then the target's slug.\n const relationName = relation.relationName ?? propertyKey ?? toSnakeCase(targetCollection.slug);\n\n const shared: Pick<ResolvedRelation, \"relationName\" | \"target\" | \"targetSlug\" | \"onUpdate\" | \"onDelete\" | \"overrides\" | \"validation\"> = {\n relationName,\n target,\n targetSlug: targetCollection.slug,\n onUpdate: relation.onUpdate,\n onDelete: relation.onDelete,\n overrides: relation.overrides,\n validation: relation.validation\n };\n\n const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);\n\n switch (relation.kind) {\n case \"belongsTo\":\n return {\n ...shared,\n kind: \"belongsTo\",\n cardinality: \"one\",\n writable: true,\n shared: false,\n localKey: relation.localKey ?? generateForeignKeyName(relationName)\n };\n\n case \"hasOne\":\n return {\n ...shared,\n kind: \"hasOne\",\n cardinality: \"one\",\n writable: true,\n shared: false,\n foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName)\n };\n\n case \"hasMany\":\n return {\n ...shared,\n kind: \"hasMany\",\n cardinality: \"many\",\n writable: true,\n shared: false,\n foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName)\n };\n\n case \"manyToMany\": {\n const sourceTable = getTableName(sourceCollection);\n const targetTable = getTableName(targetCollection);\n return {\n ...shared,\n kind: \"manyToMany\",\n cardinality: \"many\",\n writable: true,\n shared: true,\n through: {\n // Sorted so both sides of the same link derive the same\n // table without having to agree in advance.\n table: relation.through?.table ?? [sourceTable, targetTable].sort().join(\"_\"),\n sourceColumn: relation.through?.sourceColumn ?? generateForeignKeyName(sourceName),\n targetColumn: relation.through?.targetColumn ?? generateForeignKeyName(relationName)\n }\n };\n }\n\n case \"via\":\n return {\n ...shared,\n kind: \"via\",\n cardinality: relation.cardinality,\n writable: false,\n // A join chain reaches rows that other parents reach too, and\n // Rebase does not know which hop, if any, is a link it owns.\n shared: true,\n joinPath: relation.joinPath\n };\n\n default: {\n // Exhaustive: a new kind is a compile error here, not a silent\n // fall-through to whatever shape happened to match first.\n const exhaustive: never = relation;\n throw new Error(`Unknown relation kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n","import { CollectionConfig, getDataSourceCapabilities, Property, ResolvedRelation, RelationProperty } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\nimport { resolveRelation } from \"./resolve-relation\";\n\n/**\n * Whether the target rows are shared with other parents — a many-to-many, or a\n * multi-hop `via` chain.\n *\n * Decides what a write \"through\" the relation may touch: a shared target\n * belongs to every parent that links it, so the parent owns the *link* and not\n * the row. The backend enforces that (an unlink rather than a delete) and the\n * admin renders it (remove-from-parent rather than delete).\n *\n * Now a field on the resolved relation rather than a re-derivation, so both\n * sides read the same answer instead of each computing one.\n */\nexport function isJunctionBackedRelation(relation: ResolvedRelation): boolean {\n return relation.shared;\n}\n\n/** WeakMap cache — same collection instance always yields the same relation map. */\nconst _resolvedRelationsCache = new WeakMap<CollectionConfig, Record<string, ResolvedRelation>>();\n\n/**\n * Every relation a collection declares, keyed by the name it is addressed by.\n *\n * A relation reaches the map from either of two places — the collection's\n * `relations` array, or a `relation` property that declares one inline — and is\n * keyed by its resolved `relationName`, which is what a nested path segment,\n * an `include` key and an admin tab all match against.\n *\n * Resolution no longer swallows failures. It used to wrap each relation in a\n * `try/catch` that dropped anything it could not work out, so a\n * mis-declared relation silently vanished instead of being reported; with the\n * kind declared, the only remaining failure is a `target` that does not resolve,\n * which is worth hearing about.\n */\nexport function resolveCollectionRelations(\n collection: CollectionConfig\n): Record<string, ResolvedRelation> {\n const cached = _resolvedRelationsCache.get(collection);\n if (cached) return cached;\n\n if (!getDataSourceCapabilities(collection.engine).supportsRelations) return {};\n\n const relations: Record<string, ResolvedRelation> = {};\n\n for (const relation of collection.relations ?? []) {\n const resolved = resolveRelation(relation, collection);\n relations[resolved.relationName] = resolved;\n }\n\n // A property declaring a relation inline is registered under the property\n // key as well: the fetch layer hydrates the result back onto that key, and\n // it is the name the admin addresses the field by.\n for (const [propertyKey, property] of Object.entries(collection.properties ?? {})) {\n if ((property as Property)?.type !== \"relation\") continue;\n const declared = (property as RelationProperty).relation;\n if (!declared || relations[propertyKey]) continue;\n\n relations[propertyKey] = resolveRelation(declared, collection, propertyKey);\n }\n\n _resolvedRelationsCache.set(collection, relations);\n return relations;\n}\n\nexport function getTableName(collection: CollectionConfig): string {\n if (getDataSourceCapabilities(collection.engine).supportsRelations) {\n return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n }\n return toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n}\n\nexport function getTableVarName(tableName: string): string {\n return tableName.replace(/_([a-z])/g, (_, char) => char.toUpperCase());\n}\n\nexport function getEnumVarName(tableName: string, propName: string): string {\n const tableVar = getTableVarName(tableName);\n const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);\n return `${tableVar}${propVar}`;\n}\n\nexport function getColumnName(fullColumn: string): string {\n return fullColumn.includes(\".\") ? fullColumn.split(\".\").pop()! : fullColumn;\n}\n\n/**\n * Look up a relation by key with forgiving normalization.\n *\n * `resolveCollectionRelations` stores each relation under a single canonical\n * key (no aliases). This helper tries the given key as-is, then falls back to\n * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)\n * so that callers that receive a key from external input (URL path segments,\n * user-provided config, etc.) can still find the right entry.\n */\nexport function findRelation(\n resolvedRelations: Record<string, ResolvedRelation>,\n key: string\n): ResolvedRelation | undefined {\n // Exact match first\n if (resolvedRelations[key]) return resolvedRelations[key];\n\n // Try slug form (e.g. \"company_id\" → \"company-id\")\n const slugKey = key.replace(/_/g, \"-\");\n if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];\n\n // Try snake_case form (e.g. \"company-id\" → \"company_id\")\n const snakeKey = key.replace(/-/g, \"_\");\n if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];\n\n return undefined;\n}\n","import {\n ArrayProperty,\n AuthState,\n CollectionConfig,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n RelationProperty,\n ResolvedRelation,\n StringProperty,\n getDataSourceCapabilities,\n getDeclaredSubcollections,\n type EntityChildView\n} from \"@rebasepro/types\";\n\ntype PropertyConfig = { property: unknown; [key: string]: unknown };\nimport { isPropertyBuilder } from \"./entities\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\nimport { isDefaultFieldConfigId } from \"@rebasepro/utils\";\nimport { getIn, mergeDeep } from \"@rebasepro/utils\";\nimport { isJunctionBackedRelation, resolveCollectionRelations } from \"./relations\";\nimport { resolveRelation } from \"./resolve-relation\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, unknown> = Record<string, unknown>> = {\n property: Property\n propertyKey?: string,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}\n\nexport function resolveProperty<M extends Record<string, unknown> = Record<string, unknown>>(props: ResolvePropertyProps<M>): Property | null {\n\n const {\n property,\n ignoreMissingFields = false,\n ...rest\n } = props;\n\n let resultProperty: Property;\n\n if (isPropertyBuilder(property)) {\n const path = rest.path;\n if (!path) {\n // When path is not available (e.g. in preview contexts), skip dynamic\n // resolution and use the property as-is without dynamic modifications.\n resultProperty = property as Property;\n } else {\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicProps = property.dynamicProps?.({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n resultProperty = mergeDeep(property, dynamicProps ?? {});\n }\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty?.dynamicProps && rest.path) {\n const path = rest.path;\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicPropsResult = resultProperty.dynamicProps({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n\n if (dynamicPropsResult) {\n resultProperty = mergeDeep(resultProperty, dynamicPropsResult);\n }\n }\n\n let resolvedProperty: Property | null;\n\n if (resultProperty?.type === \"map\" && resultProperty.properties) {\n const properties = resolveProperties({\n ignoreMissingFields,\n ...rest,\n properties: resultProperty.properties\n });\n resolvedProperty = {\n ...resultProperty,\n properties\n } as Property;\n } else if (resultProperty?.type === \"array\") {\n resolvedProperty = resultProperty;\n } else if ((resultProperty?.type === \"string\" || resultProperty?.type === \"number\") && resultProperty.enum) {\n resolvedProperty = resolvePropertyEnum(resultProperty);\n } else {\n resolvedProperty = resultProperty;\n }\n\n if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {\n const cmsFields = rest.propertyConfigs;\n if (!cmsFields && !ignoreMissingFields) {\n throw Error(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property configs were provided. Use the property 'propertyConfigs' in your app config to provide them`);\n }\n const customField: PropertyConfig | undefined = cmsFields?.[resolvedProperty.propertyConfig];\n if (!customField) {\n console.warn(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property config with that key was found. Check the 'propertyConfigs' in your app config`)\n return resolvedProperty;\n }\n if (customField.property) {\n const restConfigProperty = { ...customField.property } as Record<string, unknown>;\n delete restConfigProperty.propertyConfig;\n const customFieldProperty = resolveProperty({\n property: { name: \"\",\n...restConfigProperty } as Property,\n ignoreMissingFields,\n ...rest\n });\n if (customFieldProperty) {\n resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);\n }\n }\n\n }\n\n return resolvedProperty;\n}\n\n/**\n * The resolved relation a relation property refers to.\n *\n * Normalization stamps `resolvedRelation` onto the property, so this is usually\n * a field read. It falls back to resolving from the collection for properties\n * that never went through the registry — a preview, or a form rendered straight\n * from an authored config.\n */\nexport function resolveRelationProperty(\n property: RelationProperty,\n collection: CollectionConfig,\n propertyKey?: string\n): ResolvedRelation {\n if (property.resolvedRelation) return property.resolvedRelation;\n\n if (property.relation) {\n return resolveRelation(property.relation, collection, propertyKey);\n }\n\n const name = propertyKey ?? \"\";\n const declared = resolveCollectionRelations(collection)[name];\n if (!declared) {\n throw Error(\n `Relation property '${name || \"(unnamed)\"}' on '${collection.slug}' declares no \\`relation\\`, ` +\n \"and the collection has no relation of that name.\"\n );\n }\n return declared;\n}\n\n/**\n * Resolve enum aliases for a string or number property\n * @param property\n */\nexport function resolvePropertyEnum(property: StringProperty | NumberProperty): StringProperty | NumberProperty {\n if (typeof property.enum === \"object\") {\n return {\n ...property,\n enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []\n };\n }\n return property as StringProperty | NumberProperty;\n}\n\n/**\n * Resolve enums and arrays for properties\n * @param properties\n * @param value\n */\nexport function resolveProperties<M extends Record<string, unknown>>({\n propertyKey,\n properties,\n ignoreMissingFields,\n ...props\n}: {\n propertyKey?: string,\n properties: Properties,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}): Properties {\n return Object.entries<Property>(properties as Record<string, Property>)\n .map(([key, property]) => {\n const childResolvedProperty = resolveProperty({\n propertyKey: propertyKey ? `${propertyKey}.${key}` : undefined,\n property: property,\n ignoreMissingFields,\n ...props\n });\n if (!childResolvedProperty) return {};\n return {\n [key]: childResolvedProperty\n };\n })\n .filter((a) => a !== null)\n .reduce((a, b) => ({ ...a,\n...b }), {}) as Properties;\n}\n\nexport function resolveArrayProperties<M>({\n propertyKey,\n property,\n ignoreMissingFields = false,\n ...props\n}: {\n propertyKey?: string,\n property: ArrayProperty,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}): Property[] {\n const propertyValue = propertyKey ? getIn(props.values, propertyKey) : undefined;\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n return property.of.map((p, index) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: p as Property,\n ignoreMissingFields,\n ...props,\n index\n });\n }) as Property[];\n } else {\n const of = property.of;\n const resolvedProperties = getArrayResolvedProperties({\n propertyValue,\n propertyKey,\n property,\n ignoreMissingFields,\n ...props\n });\n const {\n values,\n previousValues,\n ...rest\n } = props;\n const ofProperty = resolveProperty({ // we don't want to pass the values of the parent entity\n property: of,\n ignoreMissingFields,\n ...rest\n });\n if (!ofProperty && !ignoreMissingFields)\n throw Error(\"When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property\")\n return resolvedProperties;\n }\n } else if (property.oneOf) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const resolvedProperties: Property[] = Array.isArray(propertyValue)\n ? propertyValue.map((v, index) => {\n const type = v && v[typeField];\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return null;\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: childProperty,\n ignoreMissingFields,\n ...props\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n return resolvedProperties;\n } else if (!property.columnType) {\n // An array with neither `of`/`oneOf` nor a `columnType` describes no element\n // type, so nothing can be generated or rendered from it.\n //\n // The escape hatch used to be `ui.Field` — \"a custom component can render\n // anything\" — which made a *presentation* field decide whether a schema was\n // valid, in code the Postgres generator runs. `columnType` is the same escape\n // hatch stated as data: `columnType: \"text[]\"` says what the column holds,\n // which is what both the generator and the form actually need.\n throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or a \\`columnType\\` such as \"text[]\"`);\n } else {\n return [];\n }\n\n}\n\nexport function getArrayResolvedProperties({\n propertyKey,\n propertyValue,\n property,\n ...props\n}: {\n propertyValue: unknown,\n propertyKey?: string,\n property: ArrayProperty,\n ignoreMissingFields: boolean,\n values?: object;\n previousValues?: object;\n path?: string;\n entityId?: string | number;\n index?: number;\n propertyConfigs?: Record<string, PropertyConfig>;\n authController: AuthState;\n}) {\n\n const of = property.of;\n if (!of)\n throw Error(\n `Trying to resolve an array property (${propertyKey}) without providing an 'of' property`\n )\n return Array.isArray(propertyValue)\n ? propertyValue.map((v: unknown, index: number) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: Array.isArray(of) ? of[index] : of,\n ...props,\n index\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n}\n\nexport function resolveEnumValues(input: EnumValues): EnumValueConfig[] | undefined {\n if (typeof input === \"object\") {\n return Object.entries(input).map(([id, value]) =>\n (typeof value === \"string\"\n ? {\n id,\n label: value\n }\n : value));\n } else if (Array.isArray(input)) {\n return input as EnumValueConfig[];\n } else {\n return undefined;\n }\n}\n\n\n/**\n * The lists rendered inside an entity view of `collection` — its tabs.\n *\n * The single derivation. There used to be two that disagreed: this one, and a\n * copy in `CollectionRegistry.normalizeCollection` that stamped each child with\n * the *target collection's* slug instead of the relation key. Since the\n * registry ran first and cached its answer onto `childCollections`, its version\n * was the one that won, and the frontend addressed child listings by a segment\n * the backend could not resolve.\n *\n * Order of precedence:\n * 1. `childCollections` — the explicit escape hatch for custom drivers.\n * 2. `subcollections` on an engine that has real containment (Firestore).\n * 3. many-relations on an engine that has relations (SQL).\n */\nexport function getEntityChildViews<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): EntityChildView[] {\n const asSubcollections = (collections: CollectionConfig<Record<string, unknown>>[]): EntityChildView[] =>\n collections.filter(Boolean).map(child => ({\n key: child.slug,\n collection: child,\n source: { kind: \"subcollection\" as const }\n }));\n\n if (collection.childCollections) {\n return asSubcollections(collection.childCollections() ?? []);\n }\n\n const capabilities = getDataSourceCapabilities(collection.engine);\n\n const declaredSubcollections = getDeclaredSubcollections(collection);\n if (capabilities.supportsSubcollections && declaredSubcollections) {\n return asSubcollections(declaredSubcollections() ?? []);\n }\n\n if (!capabilities.supportsRelations) return [];\n\n const resolvedRelations = resolveCollectionRelations(collection);\n const views: EntityChildView[] = [];\n const seen = new Set<string>();\n\n // Keyed by the map key, not by `relationName`: the map key is what\n // `findRelation` matches a path segment against, so it is the only one that\n // addresses the same relation on both sides of the wire. The map registers\n // some relations twice — once canonically, once under the declaring\n // property key — so dedupe on the underlying relation.\n for (const [relationKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.cardinality !== \"many\") continue;\n\n const identity = relation.relationName ?? relationKey;\n if (seen.has(identity)) continue;\n\n let target: CollectionConfig | undefined;\n try {\n target = relation.target();\n } catch {\n continue;\n }\n if (!target) continue;\n seen.add(identity);\n\n // A name given to the declaring property is the author naming the tab.\n const declaringProperty = Object.entries((collection.properties ?? {}) as Record<string, Property>)\n .find(([propKey, p]) => p.type === \"relation\" && ((p as RelationProperty).relation?.relationName ?? propKey) === identity);\n const customName = declaringProperty?.[1]?.name;\n\n const base: CollectionConfig<Record<string, unknown>> = {\n ...target,\n slug: relationKey,\n ...(customName ? { name: customName,\nsingularName: customName } : {})\n } as CollectionConfig<Record<string, unknown>>;\n\n views.push({\n key: relationKey,\n collection: (relation.overrides ? mergeDeep(base, relation.overrides) : base) as CollectionConfig<Record<string, unknown>>,\n source: {\n kind: \"relation\",\n relationKey,\n mode: isJunctionBackedRelation(relation) ? \"linked\" : \"owned\",\n targetSlug: target.slug\n }\n });\n }\n\n return views;\n}\n\n/**\n * The child views of `collection` as bare collections.\n *\n * The flattened view of {@link getEntityChildViews}, for navigation code that\n * only needs to match a path segment against a slug. Anything that cares *what\n * kind* of list it is showing — chiefly the admin, which must not offer a\n * global delete on a shared row — should read the views instead.\n */\nexport function getSubcollections<M extends Record<string, unknown> = Record<string, unknown>>(collection: CollectionConfig<M>): CollectionConfig<Record<string, unknown>>[] {\n return getEntityChildViews(collection).map(view => view.collection);\n}\n","import { ANONYMOUS_USER_ID, LiteralPolicyOperand, PolicyExpression, policy } from \"@rebasepro/types\";\n\n/**\n * A tiny, regex-based SQL \"parser\" for security rules.\n *\n * This is NOT a full SQL parser. It is designed to handle the subset of SQL\n * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the\n * optimistic client-side UI decision.\n *\n * It handles:\n * - `field = 'literal'`\n * - `field != 'literal'`\n * - `field = current_setting('app.uid')` (or the legacy `app.user_id`)\n * - `A AND B`, `A OR B` — only where the keyword is at the top level\n * - `true`\n * - `IN (...)` (as optimistic true)\n *\n * For anything it doesn't understand, it returns a `raw` expression, which\n * the evaluator treats as \"unknown\" (and usually optimistic true).\n *\n * **This output also round-trips back into DDL** via `policyToPostgres` (the\n * schema/policy generators), so decomposing a clause the parser only partly\n * understands is not a cosmetic mistake — it emits invalid SQL. When in doubt,\n * prefer `raw`: it is reproduced verbatim.\n */\n/** True when `keyword` starts at `i` as a standalone word. */\nfunction isKeywordAt(upper: string, i: number, keyword: string): boolean {\n if (!upper.startsWith(keyword, i)) return false;\n const before = i === 0 ? \" \" : upper[i - 1];\n const after = upper[i + keyword.length] ?? \" \";\n return /[\\s()]/.test(before) && /[\\s()]/.test(after);\n}\n\n/**\n * Split `sql` on a boolean keyword, but only where it sits at paren depth 0 and\n * outside a string literal. Returns null when it never does, so the caller\n * leaves the clause alone.\n *\n * This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the\n * `AND` inside\n * `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = auth.uid())`\n * split the expression, and re-emitting the halves produced\n * `(EXISTS (...) AND m.user_id = auth.uid())`\n * where `m` is no longer in scope — SQL that Postgres rejects outright with\n * \"missing FROM-clause entry for table\". Returning null instead keeps such a\n * clause as a `raw` expression, which round-trips verbatim.\n */\nfunction splitTopLevel(sql: string, keyword: \"AND\" | \"OR\"): string[] | null {\n const upper = sql.toUpperCase();\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let start = 0;\n\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n if (inString) {\n if (ch === \"'\") {\n if (sql[i + 1] === \"'\") i++; // '' escapes a quote inside a literal\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") { depth++; continue; }\n if (ch === \")\") { depth--; continue; }\n if (depth === 0 && isKeywordAt(upper, i, keyword)) {\n parts.push(sql.slice(start, i));\n i += keyword.length - 1;\n start = i + 1;\n }\n }\n\n if (parts.length === 0) return null;\n parts.push(sql.slice(start));\n const trimmedParts = parts.map(p => p.trim()).filter(p => p.length > 0);\n return trimmedParts.length > 1 ? trimmedParts : null;\n}\n\n/** Drop redundant wrapping parens (`(a AND b)` → `a AND b`), never `(a) AND (b)`. */\nfunction stripOuterParens(sql: string): string {\n let s = sql.trim();\n for (;;) {\n if (!s.startsWith(\"(\") || !s.endsWith(\")\")) return s;\n let depth = 0;\n let inString = false;\n let wraps = true;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0 && i < s.length - 1) { wraps = false; break; }\n }\n }\n if (!wraps) return s;\n s = s.slice(1, -1).trim();\n }\n}\n\nexport function sqlToPolicy(sql: string): PolicyExpression {\n const trimmed = stripOuterParens(sql.trim());\n\n if (trimmed.toLowerCase() === \"true\") return policy.true();\n if (trimmed.toLowerCase() === \"false\") return policy.false();\n\n // Handle roles overlap (&&)\n // Matches: string_to_array(auth.roles(), ',') && ARRAY['admin', 'editor']\n const overlapMatch = trimmed.match(/^string_to_array\\s*\\(\\s*auth\\.roles\\(\\)\\s*,\\s*','\\s*\\)\\s*&&\\s*ARRAY\\s*\\[(.+)\\]$/i);\n if (overlapMatch) {\n const roles = overlapMatch[1].split(\",\").map(s => s.trim().replace(/^'|'$/g, \"\"));\n return policy.rolesOverlap(roles);\n }\n\n // Handle roles containment (@>)\n // Matches: string_to_array(auth.roles(), ',') @> ARRAY['admin']\n const containMatch = trimmed.match(/^string_to_array\\s*\\(\\s*auth\\.roles\\(\\)\\s*,\\s*','\\s*\\)\\s*@>\\s*ARRAY\\s*\\[(.+)\\]$/i);\n if (containMatch) {\n const roles = containMatch[1].split(\",\").map(s => s.trim().replace(/^'|'$/g, \"\"));\n return policy.rolesContain(roles);\n }\n\n // OR binds looser than AND, so it splits first.\n const orParts = splitTopLevel(trimmed, \"OR\");\n if (orParts) return policy.or(...orParts.map(sqlToPolicy));\n\n const andParts = splitTopLevel(trimmed, \"AND\");\n if (andParts) return policy.and(...andParts.map(sqlToPolicy));\n\n // Handle = and !=\n const match = trimmed.match(/^(.+?)\\s*(!?=)\\s*(.+)$/);\n if (match) {\n const [, leftStr, op, rightStr] = match;\n const left = parseOperand(leftStr.trim());\n const right = parseOperand(rightStr.trim());\n if (left && right) {\n return policy.compare(left, op === \"=\" ? \"eq\" : \"neq\", right);\n }\n }\n\n // Fallback to raw\n return policy.raw(sql);\n}\n\n/**\n * Literals from other BaaS platforms that people compare `auth.uid()` against\n * out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on\n * `pgRoles`, one surface over: the same muscle memory inside a `using:` string\n * is the more dangerous spelling, because it inverts a rule instead of\n * emptying a table.\n */\nconst FOREIGN_CONVENTION_UIDS: Record<string, string> = {\n anon: \"Supabase\",\n authenticated: \"Supabase\",\n service_role: \"Supabase\"\n};\n\n/** A clause that reads as a lockdown but admits anonymous callers. */\nexport interface AnonymousGrantRisk {\n /** Which spelling was found. */\n pattern: \"foreign-uid-literal\" | \"uid-not-null\";\n /** The offending fragment — the literal, or the SQL that is a tautology. */\n detail: string;\n /** Why it admits anonymous callers, and what to write instead. */\n explanation: string;\n}\n\n/** `auth.uid() IS NOT NULL` in raw SQL, the clause that is always true. */\nconst UID_NOT_NULL = /auth\\.uid\\(\\)\\s+IS\\s+NOT\\s+NULL/i;\n\n/**\n * Find clauses that read as \"signed-in users only\" but admit anonymous callers.\n *\n * Both spellings come from the same place — Supabase, where `auth.uid()` really\n * is NULL for an anonymous request. Rebase substitutes\n * {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which\n * is how the trusted *server* context is recognised), so:\n *\n * - `auth.uid() IS NOT NULL` is a tautology on the user path, and\n * - `auth.uid() != 'anon'` compares against a string no caller ever has.\n *\n * Either one turns a lockdown into a full grant, and neither looks wrong. No\n * real user id is ever one of these literals, and a user-context request is\n * never NULL, so a match is always a mistake rather than a deliberate check.\n *\n * Structured expressions are checked too, not just parsed SQL: `policy.compare`\n * can spell the same mistake.\n */\nexport function findAnonymousGrants(expr: PolicyExpression): AnonymousGrantRisk[] {\n const found: AnonymousGrantRisk[] = [];\n\n const visit = (e: PolicyExpression): void => {\n switch (e.kind) {\n case \"and\":\n case \"or\":\n e.operands.forEach(visit);\n return;\n case \"not\":\n visit(e.operand);\n return;\n case \"existsIn\":\n visit(e.where);\n return;\n case \"raw\":\n if (UID_NOT_NULL.test(e.sql)) {\n found.push({\n pattern: \"uid-not-null\",\n detail: e.sql,\n explanation: \"`auth.uid() IS NOT NULL` is true for every request that came from a client, \" +\n `including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. ` +\n \"Use `condition: policy.authenticated()` to mean \\\"signed in\\\".\"\n });\n }\n return;\n case \"compare\": {\n const literal = [e.left, e.right].find(o => o.kind === \"literal\") as LiteralPolicyOperand | undefined;\n const comparesUid = e.left.kind === \"authUid\" || e.right.kind === \"authUid\";\n if (!comparesUid || typeof literal?.value !== \"string\") return;\n const platform = FOREIGN_CONVENTION_UIDS[literal.value];\n if (!platform) return;\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal.value,\n explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous ` +\n `request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for ` +\n \"every caller. Use `condition: policy.authenticated()` to mean \\\"signed in\\\".\"\n });\n return;\n }\n default:\n return;\n }\n };\n\n visit(expr);\n return found;\n}\n\nfunction parseOperand(str: string) {\n // current_setting('app.uid') or auth.uid(). `app.user_id` is the\n // pre-rename spelling and stays parseable: policies are data, so a\n // database provisioned before the rename still holds rules written\n // against it, and round-tripping one must not silently drop the operand.\n if (/current_setting\\s*\\(\\s*'app\\.(uid|user_id)'\\s*\\)/i.test(str) || /auth\\.uid\\(\\)/i.test(str)) {\n return policy.authUid();\n }\n\n // Literal string: 'value'\n const stringMatch = str.match(/^'(.+)'$/);\n if (stringMatch) {\n return policy.literal(stringMatch[1]);\n }\n\n // Bare field name\n if (/^\\w+$/.test(str)) {\n return policy.field(str);\n }\n\n return null;\n}\n","import { PolicyExpression, SecurityRule, policy } from \"@rebasepro/types\";\nimport { sqlToPolicy } from \"./sqlToPolicy\";\n\n/**\n * The normalized `USING` / `WITH CHECK` conditions for a single security rule,\n * expressed in the engine-agnostic {@link PolicyExpression} model.\n *\n * A `null` clause means \"this rule contributes no condition for that clause\";\n * consumers apply the default (Postgres denies with `false`).\n */\nexport interface RuleConditions {\n usingExpr: PolicyExpression | null;\n withCheckExpr: PolicyExpression | null;\n}\n\n/**\n * Desugars a {@link SecurityRule} — its `access`/`ownerField`/`roles` shortcuts,\n * structured `condition`/`check`, and raw `using`/`withCheck` — into a single\n * normalized {@link PolicyExpression} pair.\n *\n * **This is the linchpin against drift:** both the Postgres DDL generators and\n * the client-side evaluator consume this one function, so there is exactly one\n * definition of what a rule means. In particular, application `roles` are folded\n * into the expression here (AND'd with the base condition, matching how Postgres\n * generates the clause) rather than being handled separately by each consumer.\n */\nexport function securityRuleToConditions(rule: SecurityRule): RuleConditions {\n return {\n usingExpr: withRoles(baseUsing(rule), rule),\n withCheckExpr: withRoles(baseWithCheck(rule), rule)\n };\n}\n\nfunction baseUsing(rule: SecurityRule): PolicyExpression | null {\n if (rule.condition) return rule.condition;\n if (rule.using != null) return sqlToPolicy(rule.using);\n if (rule.access === \"public\") return policy.true();\n if (rule.ownerField) return policy.compare(policy.field(rule.ownerField), \"eq\", policy.authUid());\n return null;\n}\n\nfunction baseWithCheck(rule: SecurityRule): PolicyExpression | null {\n if (rule.check) return rule.check;\n if (rule.withCheck != null) return sqlToPolicy(rule.withCheck);\n // No explicit WITH CHECK → fall back to the USING condition, matching\n // PostgreSQL's own default behavior.\n return baseUsing(rule);\n}\n\n/**\n * AND the base condition with an application-role check, or produce a roles-only\n * condition when there is no base. Mirrors the Postgres generator so that a\n * role-scoped restrictive rule denies exactly the same set of users on both\n * sides.\n */\nfunction withRoles(base: PolicyExpression | null, rule: SecurityRule): PolicyExpression | null {\n if (!rule.roles || rule.roles.length === 0) return base;\n const rolesExpr = policy.rolesOverlap(rule.roles);\n if (rule.mode === \"restrictive\") {\n // Restrictive rule: applies ONLY if user has the roles.\n // If user DOES NOT have the roles, they are NOT restricted (passes).\n // If user HAS the roles, they must pass the base condition.\n // Logical equivalent: NOT(roles) OR base\n return base ? policy.or(policy.not(rolesExpr), base) : policy.not(rolesExpr);\n }\n return base ? policy.and(base, rolesExpr) : rolesExpr;\n}\n","import { ANONYMOUS_USER_ID, CollectionConfig, PolicyExpression, PolicyOperand, PolicyCompareOperator, Property, ExistsInPolicyExpression } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { getTableName } from \"../relations\";\n\n/**\n * Options for {@link policyToPostgres}.\n */\nexport interface PolicyCompileOptions {\n /**\n * Resolve a collection by slug. Required to compile\n * {@link ExistsInPolicyExpression} (`policy.existsIn`) — the compiler needs\n * the joined collection to derive its table name / schema. When omitted, the\n * join table falls back to a snake_cased slug.\n */\n resolveCollection?: (slug: string) => CollectionConfig | undefined;\n}\n\n/**\n * The lexical scope threaded through compilation. It changes when we descend\n * into an `existsIn` subquery: inside it, `field` refers to the joined table\n * (aliased) while `outerField` refers to the outer RLS row (table-qualified).\n */\ninterface CompileScope {\n /** Collection whose columns a bare `field` operand resolves against. */\n fieldCollection?: CollectionConfig;\n /** SQL prefix for `field` operands (`\"\"` at top level, `\"alias\".` in a subquery). */\n fieldPrefix: string;\n /** The outer RLS collection, for `outerField` operands. */\n outerCollection?: CollectionConfig;\n /** SQL prefix for `outerField` operands (`\"\"` at top level, `\"schema\".\"table\".` in a subquery). */\n outerPrefix: string;\n resolveCollection?: (slug: string) => CollectionConfig | undefined;\n /** Monotonic counter for generating unique subquery aliases. */\n alias: { n: number };\n}\n\n/**\n * Compiles a {@link PolicyExpression} to a PostgreSQL boolean SQL string,\n * suitable for a `USING (...)` / `WITH CHECK (...)` clause.\n *\n * This is one of the two consumers of the shared policy model (the other being\n * {@link evaluatePolicy}); the Postgres schema generators call it so that DDL\n * and the admin UI derive from the exact same expression.\n */\nexport function policyToPostgres(expr: PolicyExpression, collection?: CollectionConfig, options?: PolicyCompileOptions): string {\n return compile(expr, {\n fieldCollection: collection,\n fieldPrefix: \"\",\n outerCollection: collection,\n outerPrefix: \"\",\n resolveCollection: options?.resolveCollection,\n alias: { n: 0 }\n });\n}\n\nfunction compile(expr: PolicyExpression, scope: CompileScope): string {\n switch (expr.kind) {\n case \"true\":\n return \"true\";\n case \"false\":\n return \"false\";\n case \"and\":\n return expr.operands.length === 0\n ? \"true\"\n : expr.operands.map(o => `(${compile(o, scope)})`).join(\" AND \");\n case \"or\":\n return expr.operands.length === 0\n ? \"false\"\n : expr.operands.map(o => `(${compile(o, scope)})`).join(\" OR \");\n case \"not\":\n return `NOT (${compile(expr.operand, scope)})`;\n case \"compare\": {\n // `auth.uid()` returns text; cast the column side so uuid / integer\n // id columns compare cleanly instead of failing with\n // \"operator does not exist: uuid = text\" at CREATE POLICY time.\n const castForAuthUid = (operand: PolicyOperand, sqlText: string, other: PolicyOperand): string =>\n other.kind === \"authUid\" && (operand.kind === \"field\" || operand.kind === \"outerField\")\n ? `(${sqlText})::text`\n : sqlText;\n const leftSql = castForAuthUid(expr.left, operandToSql(expr.left, scope), expr.right);\n const rightSql = castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);\n return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;\n }\n case \"rolesOverlap\":\n return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;\n case \"rolesContain\":\n return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;\n case \"authenticated\":\n // `IS NOT NULL` alone is a tautology on the user path: every\n // user-context request sets `app.uid`, and an anonymous one sets\n // it to the sentinel. Excluding the sentinel is what makes this mean\n // \"signed in\" rather than \"anyone at all\".\n return `auth.uid() IS NOT NULL AND auth.uid() <> ${quoteLiteral(ANONYMOUS_USER_ID)}`;\n case \"serverContext\":\n // Only the built-in server flows leave `app.uid` unset.\n return \"auth.uid() IS NULL\";\n case \"existsIn\":\n return compileExistsIn(expr, scope);\n case \"raw\":\n // Full-power escape hatch: `{column}` denotes a column of the outer\n // RLS row. It must be table-qualified, not bare: raw SQL may open its\n // own subquery over the same table, and there a bare name binds to the\n // inner scope, collapsing `m.x = {x}` into the tautology `m.x = m.x`.\n return expr.sql.replace(/\\{(\\w+)\\}/g, (_, col) =>\n `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);\n }\n}\n\n/**\n * Compiles `existsIn` to a correlated `EXISTS (SELECT 1 FROM <join> WHERE ...)`.\n * Inside the subquery, `field` operands bind to the aliased join table and\n * `outerField` operands bind to the (table-qualified) outer RLS row.\n */\nfunction compileExistsIn(expr: ExistsInPolicyExpression, scope: CompileScope): string {\n const join = scope.resolveCollection?.(expr.collection);\n const joinTable = join ? getTableName(join) : toSnakeCase(expr.collection);\n const joinSchema = schemaOf(join) ?? schemaOf(scope.outerCollection) ?? \"public\";\n const alias = `_ex${scope.alias.n++}`;\n\n // `outerField` inside the subquery must be qualified with the outer table,\n // otherwise a bare column name would bind to the joined table instead.\n const outerPrefix = outerQualifier(scope);\n\n const innerScope: CompileScope = {\n fieldCollection: join,\n fieldPrefix: `\"${alias}\".`,\n outerCollection: scope.outerCollection,\n outerPrefix,\n resolveCollection: scope.resolveCollection,\n alias: scope.alias\n };\n return `EXISTS (SELECT 1 FROM \"${joinSchema}\".\"${joinTable}\" \"${alias}\" WHERE ${compile(expr.where, innerScope)})`;\n}\n\nconst COMPARE_SQL: Record<PolicyCompareOperator, string> = {\n eq: \"=\",\n neq: \"!=\",\n lt: \"<\",\n lte: \"<=\",\n gt: \">\",\n gte: \">=\"\n};\n\nfunction operandToSql(operand: PolicyOperand, scope: CompileScope): string {\n switch (operand.kind) {\n case \"field\":\n return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldCollection)}`;\n case \"outerField\":\n return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerCollection)}`;\n case \"literal\":\n return quoteLiteral(operand.value);\n case \"authUid\":\n return \"auth.uid()\";\n case \"authRoles\":\n return \"string_to_array(auth.roles(), ',')\";\n }\n}\n\n/**\n * SQL prefix that qualifies a column of the outer RLS row (`\"schema\".\"table\".`),\n * or `\"\"` when the collection is unknown.\n */\nfunction outerQualifier(scope: CompileScope): string {\n const table = scope.outerCollection ? getTableName(scope.outerCollection) : undefined;\n if (!table) return \"\";\n return `\"${schemaOf(scope.outerCollection) ?? \"public\"}\".\"${table}\".`;\n}\n\nfunction schemaOf(collection?: CollectionConfig): string | undefined {\n return (collection as { schema?: string } | undefined)?.schema || undefined;\n}\n\nfunction resolveColumnName(propName: string, collection?: CollectionConfig): string {\n const prop = collection?.properties?.[propName] as Property | undefined;\n if (prop && \"columnName\" in prop && typeof (prop as { columnName?: unknown }).columnName === \"string\") {\n return (prop as { columnName: string }).columnName;\n }\n return toSnakeCase(propName);\n}\n\nfunction quoteLiteral(value: string | number | boolean | null): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return String(value);\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/** Sorted, single-quoted `ARRAY['a','b']` — matches the generators' output. */\nfunction rolesArraySql(roles: readonly string[]): string {\n return `ARRAY[${[...roles].sort().map(r => `'${r}'`).join(\",\")}]`;\n}\n","import {\n ArrayProperty,\n BooleanProperty,\n DateProperty,\n CollectionConfig,\n FirebaseCollectionConfig,\n FirebaseProperties,\n GeopointProperty,\n InferEntityType,\n MapProperty,\n MongoDBCollectionConfig,\n MongoProperties,\n NumberProperty,\n PostgresCollectionConfig,\n PostgresProperties,\n Property,\n ReferenceProperty,\n StringProperty,\n User\n} from \"@rebasepro/types\";\n\n\n/**\n * @deprecated Use {@link defineCollection} instead — it infers property\n * types automatically (autocomplete on `titleProperty`, `sort`,\n * `propertiesOrder`, callbacks) without manual generics.\n * `buildCollection` is kept for FireCMS migration compatibility and will\n * be removed before 1.0.\n *\n * @group Builder\n */\nexport function buildCollection<\n M extends Record<string, unknown> = Record<string, unknown>,\n USER extends User = User>\n (\n collection: CollectionConfig<M, USER>\n ): CollectionConfig<M, USER> {\n return collection;\n}\n\n// ── defineCollection ─────────────────────────────────────────────────────\n// A smarter builder that uses `const` type-parameter inference (TS 5.0+)\n// to capture literal property types automatically. This gives you\n// autocomplete on `titleProperty`, `sort`, `propertiesOrder`, `fixedFilter`,\n// callbacks, etc. — without writing `as const` or passing manual generics.\n\n/**\n * Define a PostgreSQL-backed collection with full type inference.\n *\n * The `const P` generic captures literal property types from your\n * `properties` object, which enables autocomplete on `titleProperty`,\n * `sort`, `propertiesOrder`, `fixedFilter`, and entity callbacks.\n *\n * @example\n * ```ts\n * const products = defineCollection({\n * name: \"Products\",\n * slug: \"products\",\n * table: \"products\",\n * properties: {\n * name: { name: \"Name\", type: \"string\", validation: { required: true } },\n * price: { name: \"Price\", type: \"number\" },\n * },\n * titleProperty: \"name\", // ✅ autocomplete: \"name\" | \"price\"\n * sort: [\"price\", \"asc\"], // ✅ autocomplete on first element\n * });\n * ```\n *\n * @group Builder\n */\nexport function defineCollection<\n const P extends PostgresProperties,\n USER extends User = User\n>(\n collection: Omit<PostgresCollectionConfig<InferEntityType<P>, USER>, \"properties\"> & { properties: P }\n): PostgresCollectionConfig<InferEntityType<P>, USER> & { properties: P };\n\n/**\n * Define a Firestore-backed collection with full type inference.\n * @group Builder\n */\nexport function defineCollection<\n const P extends FirebaseProperties,\n USER extends User = User\n>(\n collection: Omit<FirebaseCollectionConfig<InferEntityType<P>, USER>, \"properties\"> & { properties: P }\n): FirebaseCollectionConfig<InferEntityType<P>, USER> & { properties: P };\n\n/**\n * Define a MongoDB-backed collection with full type inference.\n * @group Builder\n */\nexport function defineCollection<\n const P extends MongoProperties,\n USER extends User = User\n>(\n collection: Omit<MongoDBCollectionConfig<InferEntityType<P>, USER>, \"properties\"> & { properties: P }\n): MongoDBCollectionConfig<InferEntityType<P>, USER> & { properties: P };\n\n/**\n * Implementation — delegates to the correct overload at the type level.\n * At runtime this is a plain identity function.\n */\nexport function defineCollection(\n collection: CollectionConfig\n): CollectionConfig {\n return collection;\n}\n\n/**\n * @deprecated Use plain typed property objects with {@link defineCollection}\n * instead — `defineCollection` infers property types automatically, making\n * this wrapper unnecessary. `buildProperty` is kept for FireCMS migration\n * compatibility and will be removed before 1.0.\n *\n * @group Builder\n */\nexport function buildProperty<T, P extends Property = Property>(\n property: P\n):\n P extends StringProperty ? StringProperty :\n P extends NumberProperty ? NumberProperty :\n P extends BooleanProperty ? BooleanProperty :\n P extends DateProperty ? DateProperty :\n P extends GeopointProperty ? GeopointProperty :\n P extends ReferenceProperty ? ReferenceProperty :\n P extends ArrayProperty ? ArrayProperty :\n P extends MapProperty ? MapProperty : never {\n\n // SAFETY: Identity function — P is a subtype of the conditional return type by definition\n return property as unknown as ReturnType<typeof buildProperty<T, P>>;\n}\n","import { CollectionCallbacks, Properties, RebaseCallContext } from \"@rebasepro/types\";\n\n/**\n * Context passed to entity lifecycle callbacks.\n * @group Models\n */\nexport type EntityCallbackContext = RebaseCallContext;\n\n\n/**\n * Helper function to recursively check if there are any callbacks in the properties.\n */\nfunction hasPropertyCallbacks(properties: Properties, callbackName: \"afterRead\" | \"beforeSave\"): boolean {\n if (!properties) return false;\n for (const property of Object.values(properties)) {\n if (property.callbacks?.[callbackName]) return true;\n if (property.type === \"map\" && property.properties) {\n if (hasPropertyCallbacks(property.properties, callbackName)) return true;\n } else if (property.type === \"array\" && property.of) {\n const ofs = Array.isArray(property.of) ? property.of : [property.of];\n for (const of of ofs) {\n if (of.callbacks?.[callbackName]) return true;\n if (of.type === \"map\" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Recursively process properties to apply field-level hooks.\n */\nasync function processProperties(\n properties: Properties,\n values: Record<string, unknown>,\n previousValues: Record<string, unknown>,\n propsContext: unknown,\n callbackName: \"afterRead\" | \"beforeSave\"\n): Promise<Record<string, unknown>> {\n if (!values || typeof values !== \"object\") return values;\n\n const result = { ...values };\n\n for (const [key, property] of Object.entries(properties)) {\n if (result[key] === undefined) continue;\n\n let currentValue = result[key];\n const previousValue = previousValues?.[key];\n\n // 1. Array Property\n if (property.type === \"array\" && Array.isArray(currentValue)) {\n // We only support traversing single-type arrays for hooks currently to avoid complex union matching\n if (property.of && !Array.isArray(property.of)) {\n currentValue = await Promise.all(currentValue.map(async (item, index) => {\n const prevItem = Array.isArray(previousValue) ? previousValue[index] : undefined;\n // Mock a properties object to process a single item\n const singlePropData = { \"_tmp\": property.of } as Properties;\n const res = await processProperties(singlePropData, { \"_tmp\": item }, { \"_tmp\": prevItem }, propsContext, callbackName);\n return res[\"_tmp\"];\n }));\n }\n }\n // 2. Map Property\n else if (property.type === \"map\" && property.properties && typeof currentValue === \"object\") {\n currentValue = await processProperties(property.properties, currentValue as Record<string, unknown>, (previousValue ?? {}) as Record<string, unknown>, propsContext, callbackName);\n }\n\n // 3. Property's own callback\n if (property.callbacks?.[callbackName]) {\n\n const cbRes = await Promise.resolve(property.callbacks[callbackName]({\n ...(propsContext as Record<string, unknown>),\n value: currentValue,\n previousValue\n } as never));\n if (cbRes !== undefined) {\n currentValue = cbRes;\n }\n }\n\n result[key] = currentValue;\n }\n return result;\n}\n\n/**\n * Helper function to extract field-level PropertyCallbacks from a properties schema\n * and wrap them into an CollectionCallbacks object recursively.\n */\nexport const buildPropertyCallbacks = (properties: Properties): CollectionCallbacks | undefined => {\n if (!properties) return undefined;\n\n const propertyCallbacks: CollectionCallbacks = {};\n\n if (hasPropertyCallbacks(properties, \"afterRead\")) {\n propertyCallbacks.afterRead = async (props) => {\n const row = props.row;\n const processedValues = await processProperties(\n properties,\n row,\n row,\n props as unknown,\n \"afterRead\"\n );\n return { ...props.row, ...processedValues };\n };\n }\n\n if (hasPropertyCallbacks(properties, \"beforeSave\")) {\n propertyCallbacks.beforeSave = async (props) => {\n return await processProperties(\n properties,\n props.values as Record<string, unknown>,\n (props.previousValues ?? {}) as Record<string, unknown>,\n props as unknown,\n \"beforeSave\"\n );\n };\n }\n\n return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : undefined;\n};\n","import { CollectionConfig, SecurityRule, SecurityOperation, AuthCollectionConfig, PolicyExpression, isPostgresCollectionConfig, policy } from \"@rebasepro/types\";\nimport { getTableName } from \"./relations\";\n\n/**\n * Default RLS policies injected by the schema generator.\n *\n * Rebase's enforcement model is unified: authenticated (user-context) requests\n * run under the restricted `rebase_user` role, so Postgres RLS binds *every*\n * statement — reads and writes. A collection's `securityRules` are the whole\n * authorization model. The server context (auth flows, migrations,\n * `dataAsAdmin`) runs as the owner and bypasses RLS.\n *\n * Because RLS default-denies, every collection is **locked by default**: with\n * no rules, only the server context and admins can touch it. The generator\n * injects that safe baseline:\n *\n * **For every collection**\n * 1. A permissive **server-or-admin SELECT** grant.\n * 2. A permissive **server-or-admin write** grant (insert/update/delete).\n *\n * Author `securityRules` are permissive and OR together, so explicit rules only\n * *broaden* access from this locked baseline (e.g. \"users read/write their own\n * rows\").\n *\n * **For auth collections additionally**\n * 3. A permissive **self SELECT** grant (`id = auth.uid()`), so users can read\n * their own row (profile, session bootstrap) without every app re-declaring\n * it.\n * 4. A **restrictive** admin write gate. Restrictive policies are AND'd with\n * every other policy, so a write is rejected unless the caller is an admin\n * (or the server context) — even if the author also wrote a permissive rule\n * such as \"a user may edit their own row\". Without this, a permissive owner\n * rule would let a user change their own `roles`.\n *\n * The server context is recognised as `auth.uid() IS NULL` (`policy.serverContext()`)\n * — the built-in flows that run without a user (signup, migrations) set no user\n * GUC — which also lets the owner connection satisfy these policies even under\n * FORCE RLS. A *user* request never reaches that state: an anonymous one carries\n * `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.\n *\n * Opt out with `disableDefaultPolicies: true` to take full responsibility for\n * the collection's RLS.\n */\n// Expressed structurally (not as raw SQL) so the admin UI can evaluate it\n// exactly — the framework's most security-critical policies must be reflected\n// precisely, not left as un-evaluable raw clauses. Compiles to\n// `auth.uid() IS NULL OR (string_to_array(auth.roles(), ',') && ARRAY['admin'])`.\n//\n// `serverContext()`, emphatically not `not(authenticated())`: the server arm of\n// this grant must match the server context and nothing else. Anonymous visitors\n// are not signed in either, so a negated `authenticated()` would hand them the\n// server-or-admin grant on every collection's default policy.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/** Write operations that must be admin-gated by default on auth collections. */\nconst DEFAULT_GUARDED_OPS: SecurityOperation[] = [\"insert\", \"update\", \"delete\"];\n\n/** Whether a collection is flagged as an authentication collection. */\nfunction isAuthCollection(collection: CollectionConfig): boolean {\n const auth = collection.auth;\n return auth === true || (typeof auth === \"object\" && (auth as AuthCollectionConfig)?.enabled === true);\n}\n\n/** The property marked as the row id (falls back to `id`). */\nfunction getIdPropertyName(collection: CollectionConfig): string {\n for (const [name, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && (prop as { isId?: unknown }).isId) {\n return name;\n }\n }\n return \"id\";\n}\n\n/**\n * Returns the security rules that should be applied to a collection: the\n * author's explicit `securityRules` plus the framework defaults described in\n * the module doc (baseline server/admin read for all collections; self-read\n * and the admin write gate for auth collections).\n *\n * Collections that opt out via `disableDefaultPolicies` are returned unchanged.\n */\nexport function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[] {\n const explicit = [...((isPostgresCollectionConfig(collection) ? collection.securityRules : undefined) ?? [])];\n\n if (collection.disableDefaultPolicies) {\n return explicit;\n }\n\n const tableName = getTableName(collection);\n const injected: SecurityRule[] = [];\n\n // Baseline read + write: the server context and admins can always operate.\n // RLS default-denies under the user role, so without these a rule-less\n // collection would be locked to everyone — including the admin studio.\n // Author rules are permissive and broaden access from here.\n injected.push({\n name: `${tableName}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n injected.push({\n name: `${tableName}_default_admin_write`,\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n if (isAuthCollection(collection)) {\n // Self-read: a user can always read their own row.\n injected.push({\n name: `${tableName}_default_self_read`,\n operations: [\"select\"],\n condition: policy.compare(policy.field(getIdPropertyName(collection)), \"eq\", policy.authUid())\n });\n\n // Restrictive gate: AND'd with all other policies, so no permissive rule\n // (e.g. an owner \"edit your own row\" rule) can let a non-admin change\n // privileged columns like `roles`.\n injected.push({\n name: `${tableName}_require_admin_write`,\n mode: \"restrictive\",\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n }\n\n return [...explicit, ...injected];\n}\n\n/**\n * The framework defaults that {@link getEffectiveSecurityRules} would add to a\n * collection, without the author's own rules.\n *\n * These policies appear in the database under names the author never wrote, and\n * a permissive policy ORs with every other permissive policy — so someone\n * reading their `securityRules` and then the real ACL sees more access than they\n * declared. Dropping them by hand does nothing either: `db push` is declarative,\n * so the next push asserts them again. Callers use this to say, in the generated\n * DDL, which policies are injected and how to take them off.\n */\nexport function getInjectedSecurityRules(collection: CollectionConfig): SecurityRule[] {\n if (collection.disableDefaultPolicies) return [];\n\n const explicitCount = ((isPostgresCollectionConfig(collection) ? collection.securityRules : undefined) ?? []).length;\n // getEffectiveSecurityRules appends the defaults after the author's rules,\n // so everything past the author's count is injected.\n return getEffectiveSecurityRules(collection).slice(explicitCount);\n}\n","import {\n CollectionConfig,\n PolicyExpression,\n PolicyOperand,\n Relation,\n SecurityRule,\n isPostgresCollectionConfig,\n policy\n} from \"@rebasepro/types\";\nimport { getPolicyOperations } from \"@rebasepro/utils\";\nimport { getTableName } from \"./relations\";\nimport { resolveCollectionRelations } from \"./relations\";\nimport { isManyToMany } from \"@rebasepro/types\";\nimport { securityRuleToConditions } from \"./policy/securityRuleToConditions\";\n\n/**\n * RLS derivation for many-to-many junction tables.\n *\n * A `through` relation makes the generator create a table nobody declared as a\n * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind\n * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,\n * so with the endpoints locked down, any signed-up user could still read or wipe\n * every edge between them. There is also nowhere in the config to write rules\n * for a junction, so the author could not even fix it by hand.\n *\n * The architecture here is that a junction's security is *derived*, never\n * hand-written:\n *\n * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every\n * collection gets, so the invariant holds again: every table the generator\n * creates is default-deny, and rules only broaden.\n *\n * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint\n * rows are visible — two correlated `EXISTS` subqueries. The subqueries run\n * under the caller's role, so each endpoint's own RLS filters them: junction\n * visibility delegates to the endpoints' policies, whatever they become,\n * with nothing duplicated. A public blog keeps rendering its tags; a private\n * CRM's edges are exactly as hidden as its rows.\n *\n * 3. **Writes follow the owning side's update rules.** Linking or unlinking an\n * edge *is* an edit of the owning row — tagging a post is editing the post —\n * so edge writes inherit the declaring collection's explicit permissive\n * `update` rules, each wrapped in an `EXISTS` against the owning row. Where\n * a rule cannot be embedded faithfully (see below) it is dropped, so the\n * failure mode is always *too locked*, never open. Explicit **restrictive**\n * update rules are inherited as restrictive junction rules; if one of them\n * cannot be embedded, the whole derived write grant for that side is\n * suppressed — granting without the author's gate would be looser than the\n * parent itself.\n *\n * **Embeddability.** A parent rule is embedded by moving its condition inside\n * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.\n * In that scope, `field` operands bind to the parent — which is what the author\n * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind\n * to the RLS row, which is now the junction, not the parent the author wrote\n * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`\n * (equivalent to `field` outside a subquery) is rewritten to `field`; an\n * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies\n * the rule.\n *\n * Injected parent defaults are never inherited — the junction's own baseline\n * already covers the server/admin plane, and an auth collection's restrictive\n * `require_admin_write` gate exists to protect privileged parent *columns*,\n * which an edge write cannot touch. Inheriting it would stop users managing\n * e.g. their own interests through a `users_interests` junction for no gain.\n *\n * Everything flows through the shared naming machinery, so the Studio\n * recognises these policies as generated instead of offering to \"import\" them.\n */\n\n/** One side of a junction: the collection and the FK column pointing at it. */\nexport interface JunctionEndpoint {\n collection: CollectionConfig;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/** A collection that declares the `through` relation (owns the edge semantics). */\nexport interface JunctionDeclaringSide extends JunctionEndpoint {\n relation: Relation;\n}\n\nexport interface JunctionSpec {\n /** Bare table name (schema stripped). */\n table: string;\n /** Schema the junction is created in — mirrors the CREATE TABLE path. */\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [JunctionEndpoint, JunctionEndpoint];\n /** Every collection that declares a relation through this table. */\n declaringSides: JunctionDeclaringSide[];\n}\n\n// Mirrors auth-default-policies: the server context or an admin.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/**\n * Walk every collection's resolved relations and aggregate the junction tables\n * they declare. Two collections may declare the same junction from opposite\n * sides (posts→tags and tags→posts through `posts_tags`); both become\n * `declaringSides` of one spec, so derived write grants consider both.\n */\nexport function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec> {\n const specs = new Map<string, JunctionSpec>();\n\n for (const collection of collections) {\n const resolved = resolveCollectionRelations(collection);\n for (const relation of Object.values(resolved)) {\n // Narrowed rather than probed: only a many-to-many has a junction,\n // and only after narrowing is `through` guaranteed complete.\n if (!isManyToMany(relation)) continue;\n\n const targetCollection: CollectionConfig | undefined = relation.target();\n if (!targetCollection) continue;\n\n const rawName = relation.through.table;\n // The CREATE TABLE path strips a schema prefix from the name but\n // still creates in \"public\"; the policies must target the same\n // table, so mirror that behaviour exactly.\n const table = rawName.includes(\".\") ? rawName.split(\".\").pop()! : rawName;\n const schema = \"public\";\n\n const source: JunctionDeclaringSide = {\n collection,\n junctionColumn: relation.through.sourceColumn,\n relation\n };\n const target: JunctionEndpoint = {\n collection: targetCollection,\n junctionColumn: relation.through.targetColumn\n };\n\n const existing = specs.get(table);\n if (!existing) {\n specs.set(table, {\n table,\n schema,\n endpoints: [source, target],\n declaringSides: [source]\n });\n } else if (!existing.declaringSides.some(s => s.collection === collection)) {\n existing.declaringSides.push(source);\n }\n }\n }\n\n return specs;\n}\n\n/**\n * A synthetic CollectionConfig standing in for the junction during policy\n * compilation and naming. Its two FK columns carry explicit `columnName`s so\n * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,\n * whatever their casing.\n */\nexport function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig {\n const properties: Record<string, unknown> = {};\n for (const endpoint of spec.endpoints) {\n properties[endpoint.junctionColumn] = {\n type: \"string\",\n columnName: endpoint.junctionColumn\n };\n }\n return {\n slug: spec.table,\n name: spec.table,\n table: spec.table,\n schema: spec.schema,\n properties\n } as unknown as CollectionConfig;\n}\n\n/** The property marked as the row id (falls back to `id`). */\nfunction getIdPropertyName(collection: CollectionConfig): string {\n for (const [name, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && (prop as { isId?: unknown }).isId) {\n return name;\n }\n }\n return \"id\";\n}\n\n/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */\nfunction existsEndpoint(endpoint: JunctionEndpoint, extra?: PolicyExpression): PolicyExpression {\n const correlation = policy.compare(\n policy.field(getIdPropertyName(endpoint.collection)),\n \"eq\",\n policy.outerField(endpoint.junctionColumn)\n );\n return policy.existsIn({\n collection: endpoint.collection.slug,\n where: extra ? policy.and(correlation, extra) : correlation\n });\n}\n\n/**\n * Whether a parent-rule expression keeps its meaning when moved inside the\n * junction's `EXISTS` subquery — and the re-scoped copy if it does.\n *\n * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL\n * anywhere (its `{column}` placeholders would bind to the junction), or an\n * `outerField` inside a nested `existsIn` (it would bind to the junction while\n * the author meant the parent, and no operand can express \"the middle scope\").\n * Top-level `outerField`s are rewritten to `field`, which is what they meant.\n */\nexport function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {\n switch (expr.kind) {\n case \"raw\":\n return null;\n case \"and\":\n case \"or\": {\n const parts: PolicyExpression[] = [];\n for (const child of expr.operands) {\n const embedded = embedParentExpression(child, depth);\n if (!embedded) return null;\n parts.push(embedded);\n }\n return expr.kind === \"and\" ? policy.and(...parts) : policy.or(...parts);\n }\n case \"not\": {\n const embedded = embedParentExpression(expr.operand, depth);\n return embedded ? policy.not(embedded) : null;\n }\n case \"existsIn\": {\n const where = embedParentExpression(expr.where, depth + 1);\n return where ? policy.existsIn({ collection: expr.collection, where }) : null;\n }\n case \"compare\": {\n const left = embedOperand(expr.left, depth);\n const right = embedOperand(expr.right, depth);\n if (!left || !right) return null;\n return { ...expr, left, right };\n }\n default:\n // Leaf expressions with no field references (true, false,\n // serverContext, authenticated, rolesOverlap, rolesContain) are\n // position-independent.\n return expr;\n }\n}\n\n/** Re-scope an operand, or return `null` if its binding cannot be preserved. */\nfunction embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {\n if (operand.kind === \"outerField\") {\n // Outside a subquery, outerField ≡ field: the author meant their own\n // row, which after embedding is the EXISTS's joined table → field.\n if (depth === 0) return policy.field(operand.name);\n // Inside the author's own existsIn it meant the parent row; after\n // embedding it would bind to the junction. Not expressible.\n return null;\n }\n return operand;\n}\n\n/** Does the rule cover the `update` operation? */\nfunction coversUpdate(rule: SecurityRule): boolean {\n return getPolicyOperations(rule).some(op => op === \"update\" || op === \"all\");\n}\n\n/**\n * The full derived policy set for a junction table: the locked server/admin\n * baseline, the endpoint-visibility read grant, inherited write grants, and\n * inherited restrictive gates. Returns `[]` when every declaring collection set\n * `disableDefaultPolicies` — the junction is then the author's to police, and\n * stays locked (RLS is still enabled) until they write policies for it.\n */\nexport function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[] {\n if (spec.declaringSides.every(side => side.collection.disableDefaultPolicies)) {\n return [];\n }\n\n const rules: SecurityRule[] = [];\n\n // 1. Locked baseline — same shape and naming as every collection's.\n rules.push({\n name: `${spec.table}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n rules.push({\n name: `${spec.table}_default_admin_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n // 2. Reads follow the endpoints: the edge is visible iff both rows are.\n // The EXISTS subqueries run under the caller's role, so each endpoint's\n // own RLS applies inside them — visibility is delegated, not copied.\n rules.push({\n name: `${spec.table}_default_edge_read`,\n operations: [\"select\"],\n condition: policy.and(\n existsEndpoint(spec.endpoints[0]),\n existsEndpoint(spec.endpoints[1])\n )\n });\n\n // 3. Writes follow the owning side's explicit update rules.\n const writeGrants: PolicyExpression[] = [];\n for (const side of spec.declaringSides) {\n const explicitRules = (isPostgresCollectionConfig(side.collection)\n ? side.collection.securityRules\n : undefined) ?? [];\n const updateRules = explicitRules.filter(coversUpdate);\n\n const permissive = updateRules.filter(r => r.mode !== \"restrictive\");\n const restrictive = updateRules.filter(r => r.mode === \"restrictive\");\n\n // Embed the restrictive gates first: if any of them cannot be carried\n // over, granting writes from this side would be looser than the parent\n // itself allows — so the whole side's grant is suppressed.\n const embeddedGates: PolicyExpression[] = [];\n let gatesEmbeddable = true;\n for (const gate of restrictive) {\n const using = securityRuleToConditions(gate).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (!embedded) {\n gatesEmbeddable = false;\n break;\n }\n embeddedGates.push(embedded);\n }\n if (!gatesEmbeddable) continue;\n\n const grants: PolicyExpression[] = [];\n for (const rule of permissive) {\n const using = securityRuleToConditions(rule).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (embedded) grants.push(embedded);\n }\n if (grants.length === 0) continue;\n\n // \"May update the owning row\": any permissive grant, AND every gate.\n const condition = embeddedGates.length > 0\n ? policy.and(policy.or(...grants), ...embeddedGates)\n : policy.or(...grants);\n\n writeGrants.push(existsEndpoint(side, condition));\n }\n\n if (writeGrants.length > 0) {\n rules.push({\n name: `${spec.table}_default_edge_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),\n check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)\n });\n }\n\n return rules;\n}\n","/* globals define,module */\n/*\nUsing a Universal Module Loader that should be browser, require, and AMD friendly\nhttp://ricostacruz.com/cheatsheets/umdjs.html\n*/\n;(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(factory);\n } else if (typeof exports === \"object\") {\n module.exports = factory();\n } else {\n root.jsonLogic = factory();\n }\n}(this, function() {\n \"use strict\";\n /* globals console:false */\n\n if ( ! Array.isArray) {\n Array.isArray = function(arg) {\n return Object.prototype.toString.call(arg) === \"[object Array]\";\n };\n }\n\n /**\n * Return an array that contains no duplicates (original not modified)\n * @param {array} array Original reference array\n * @return {array} New array with no duplicates\n */\n function arrayUnique(array) {\n var a = [];\n for (var i=0, l=array.length; i<l; i++) {\n if (a.indexOf(array[i]) === -1) {\n a.push(array[i]);\n }\n }\n return a;\n }\n\n var jsonLogic = {};\n var operations = {\n \"==\": function(a, b) {\n return a == b;\n },\n \"===\": function(a, b) {\n return a === b;\n },\n \"!=\": function(a, b) {\n return a != b;\n },\n \"!==\": function(a, b) {\n return a !== b;\n },\n \">\": function(a, b) {\n return a > b;\n },\n \">=\": function(a, b) {\n return a >= b;\n },\n \"<\": function(a, b, c) {\n return (c === undefined) ? a < b : (a < b) && (b < c);\n },\n \"<=\": function(a, b, c) {\n return (c === undefined) ? a <= b : (a <= b) && (b <= c);\n },\n \"!!\": function(a) {\n return jsonLogic.truthy(a);\n },\n \"!\": function(a) {\n return !jsonLogic.truthy(a);\n },\n \"%\": function(a, b) {\n return a % b;\n },\n \"log\": function(a) {\n console.log(a); return a;\n },\n \"in\": function(a, b) {\n if (!b || typeof b.indexOf === \"undefined\") return false;\n return (b.indexOf(a) !== -1);\n },\n \"cat\": function() {\n return Array.prototype.join.call(arguments, \"\");\n },\n \"substr\": function(source, start, end) {\n if (end < 0) {\n // JavaScript doesn't support negative end, this emulates PHP behavior\n var temp = String(source).substr(start);\n return temp.substr(0, temp.length + end);\n }\n return String(source).substr(start, end);\n },\n \"+\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) + parseFloat(b, 10);\n }, 0);\n },\n \"*\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) * parseFloat(b, 10);\n });\n },\n \"-\": function(a, b) {\n if (b === undefined) {\n return -a;\n } else {\n return a - b;\n }\n },\n \"/\": function(a, b) {\n return a / b;\n },\n \"min\": function() {\n return Math.min.apply(this, arguments);\n },\n \"max\": function() {\n return Math.max.apply(this, arguments);\n },\n \"merge\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return a.concat(b);\n }, []);\n },\n \"var\": function(a, b) {\n var not_found = (b === undefined) ? null : b;\n var data = this;\n if (typeof a === \"undefined\" || a===\"\" || a===null) {\n return data;\n }\n var sub_props = String(a).split(\".\");\n for (var i = 0; i < sub_props.length; i++) {\n if (data === null || data === undefined) {\n return not_found;\n }\n // Descending into data\n data = data[sub_props[i]];\n if (data === undefined) {\n return not_found;\n }\n }\n return data;\n },\n \"missing\": function() {\n /*\n Missing can receive many keys as many arguments, like {\"missing:[1,2]}\n Missing can also receive *one* argument that is an array of keys,\n which typically happens if it's actually acting on the output of another command\n (like 'if' or 'merge')\n */\n\n var missing = [];\n var keys = Array.isArray(arguments[0]) ? arguments[0] : arguments;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = jsonLogic.apply({\"var\": key}, this);\n if (value === null || value === \"\") {\n missing.push(key);\n }\n }\n\n return missing;\n },\n \"missing_some\": function(need_count, options) {\n // missing_some takes two arguments, how many (minimum) items must be present, and an array of keys (just like 'missing') to check for presence.\n var are_missing = jsonLogic.apply({\"missing\": options}, this);\n\n if (options.length - are_missing.length >= need_count) {\n return [];\n } else {\n return are_missing;\n }\n },\n };\n\n jsonLogic.is_logic = function(logic) {\n return (\n typeof logic === \"object\" && // An object\n logic !== null && // but not null\n ! Array.isArray(logic) && // and not an array\n Object.keys(logic).length === 1 // with exactly one key\n );\n };\n\n /*\n This helper will defer to the JsonLogic spec as a tie-breaker when different language interpreters define different behavior for the truthiness of primitives. E.g., PHP considers empty arrays to be falsy, but Javascript considers them to be truthy. JsonLogic, as an ecosystem, needs one consistent answer.\n\n Spec and rationale here: http://jsonlogic.com/truthy\n */\n jsonLogic.truthy = function(value) {\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n return !! value;\n };\n\n\n jsonLogic.get_operator = function(logic) {\n return Object.keys(logic)[0];\n };\n\n jsonLogic.get_values = function(logic) {\n return logic[jsonLogic.get_operator(logic)];\n };\n\n jsonLogic.apply = function(logic, data) {\n // Does this array contain logic? Only one way to find out.\n if (Array.isArray(logic)) {\n return logic.map(function(l) {\n return jsonLogic.apply(l, data);\n });\n }\n // You've recursed to a primitive, stop!\n if ( ! jsonLogic.is_logic(logic) ) {\n return logic;\n }\n\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n var i;\n var current;\n var scopedLogic;\n var scopedData;\n var initial;\n\n // easy syntax for unary operators, like {\"var\" : \"x\"} instead of strict {\"var\" : [\"x\"]}\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n // 'if', 'and', and 'or' violate the normal rule of depth-first calculating consequents, let each manage recursion as needed.\n if (op === \"if\" || op == \"?:\") {\n /* 'if' should be called with a odd number of parameters, 3 or greater\n This works on the pattern:\n if( 0 ){ 1 }else{ 2 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else{ 4 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else if( 4 ){ 5 }else{ 6 };\n\n The implementation is:\n For pairs of values (0,1 then 2,3 then 4,5 etc)\n If the first evaluates truthy, evaluate and return the second\n If the first evaluates falsy, jump to the next pair (e.g, 0,1 to 2,3)\n given one parameter, evaluate and return it. (it's an Else and all the If/ElseIf were false)\n given 0 parameters, return NULL (not great practice, but there was no Else)\n */\n for (i = 0; i < values.length - 1; i += 2) {\n if ( jsonLogic.truthy( jsonLogic.apply(values[i], data) ) ) {\n return jsonLogic.apply(values[i+1], data);\n }\n }\n if (values.length === i+1) {\n return jsonLogic.apply(values[i], data);\n }\n return null;\n } else if (op === \"and\") { // Return first falsy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( ! jsonLogic.truthy(current)) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"or\") {// Return first truthy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( jsonLogic.truthy(current) ) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"filter\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n // Return only the elements from the array in the first argument,\n // that return truthy when passed to the logic in the second argument.\n // For parity with JavaScript, reindex the returned array\n return scopedData.filter(function(datum) {\n return jsonLogic.truthy( jsonLogic.apply(scopedLogic, datum));\n });\n } else if (op === \"map\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n\n return scopedData.map(function(datum) {\n return jsonLogic.apply(scopedLogic, datum);\n });\n } else if (op === \"reduce\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n initial = typeof values[2] !== \"undefined\" ? jsonLogic.apply(values[2], data) : null;\n\n if ( ! Array.isArray(scopedData)) {\n return initial;\n }\n\n return scopedData.reduce(\n function(accumulator, current) {\n return jsonLogic.apply(\n scopedLogic,\n {current: current, accumulator: accumulator}\n );\n },\n initial\n );\n } else if (op === \"all\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n // All of an empty set is false. Note, some and none have correct fallback after the for loop\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( ! jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First falsy, short circuit\n }\n }\n return true; // All were truthy\n } else if (op === \"none\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return true;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First truthy, short circuit\n }\n }\n return true; // None were truthy\n } else if (op === \"some\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return true; // First truthy, short circuit\n }\n }\n return false; // None were truthy\n }\n\n // Everyone else gets immediate depth-first recursion\n values = values.map(function(val) {\n return jsonLogic.apply(val, data);\n });\n\n\n // The operation is called with \"data\" bound to its \"this\" and \"values\" passed as arguments.\n // Structured commands like % or > can name formal arguments while flexible commands (like missing or merge) can operate on the pseudo-array arguments\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments\n if (operations.hasOwnProperty(op) && typeof operations[op] === \"function\") {\n return operations[op].apply(data, values);\n } else if (op.indexOf(\".\") > 0) { // Contains a dot, and not in the 0th position\n var sub_ops = String(op).split(\".\");\n var operation = operations;\n for (i = 0; i < sub_ops.length; i++) {\n if (!operation.hasOwnProperty(sub_ops[i])) {\n throw new Error(\"Unrecognized operation \" + op +\n \" (failed at \" + sub_ops.slice(0, i+1).join(\".\") + \")\");\n }\n // Descending into operations\n operation = operation[sub_ops[i]];\n }\n\n return operation.apply(data, values);\n }\n\n throw new Error(\"Unrecognized operation \" + op );\n };\n\n jsonLogic.uses_data = function(logic) {\n var collection = [];\n\n if (jsonLogic.is_logic(logic)) {\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n if (op === \"var\") {\n // This doesn't cover the case where the arg to var is itself a rule.\n collection.push(values[0]);\n } else {\n // Recursion!\n values.forEach(function(val) {\n collection.push.apply(collection, jsonLogic.uses_data(val) );\n });\n }\n }\n\n return arrayUnique(collection);\n };\n\n jsonLogic.add_operation = function(name, code) {\n operations[name] = code;\n };\n\n jsonLogic.rm_operation = function(name) {\n delete operations[name];\n };\n\n jsonLogic.rule_like = function(rule, pattern) {\n // console.log(\"Is \". JSON.stringify(rule) . \" like \" . JSON.stringify(pattern) . \"?\");\n if (pattern === rule) {\n return true;\n } // TODO : Deep object equivalency?\n if (pattern === \"@\") {\n return true;\n } // Wildcard!\n if (pattern === \"number\") {\n return (typeof rule === \"number\");\n }\n if (pattern === \"string\") {\n return (typeof rule === \"string\");\n }\n if (pattern === \"array\") {\n // !logic test might be superfluous in JavaScript\n return Array.isArray(rule) && ! jsonLogic.is_logic(rule);\n }\n\n if (jsonLogic.is_logic(pattern)) {\n if (jsonLogic.is_logic(rule)) {\n var pattern_op = jsonLogic.get_operator(pattern);\n var rule_op = jsonLogic.get_operator(rule);\n\n if (pattern_op === \"@\" || pattern_op === rule_op) {\n // echo \"\\nOperators match, go deeper\\n\";\n return jsonLogic.rule_like(\n jsonLogic.get_values(rule, false),\n jsonLogic.get_values(pattern, false)\n );\n }\n }\n return false; // pattern is logic, rule isn't, can't be eq\n }\n\n if (Array.isArray(pattern)) {\n if (Array.isArray(rule)) {\n if (pattern.length !== rule.length) {\n return false;\n }\n /*\n Note, array order MATTERS, because we're using this array test logic to consider arguments, where order can matter. (e.g., + is commutative, but '-' or 'if' or 'var' are NOT)\n */\n for (var i = 0; i < pattern.length; i += 1) {\n // If any fail, we fail\n if ( ! jsonLogic.rule_like(rule[i], pattern[i])) {\n return false;\n }\n }\n return true; // If they *all* passed, we pass\n } else {\n return false; // Pattern is array, rule isn't\n }\n }\n\n // Not logic, not array, not a === match for rule.\n return false;\n };\n\n return jsonLogic;\n}));\n","import jsonLogic from \"json-logic-js\";\nimport {\n ArrayProperty,\n AuthState,\n ConditionContext,\n EnumValueConfig,\n JsonLogicRule,\n NumberProperty,\n PropertyConditions,\n Property,\n ReferenceProperty,\n StringProperty\n} from \"@rebasepro/types\";\n\n/**\n * Access a nested property from an object via dot notation.\n */\nfunction getIn(obj: Record<string, unknown> | unknown, path: string): unknown {\n if (!obj || !path) return undefined;\n return path.split(\".\").reduce((acc: unknown, part: string) => acc && (acc as Record<string, unknown>)[part], obj);\n}\n\nlet operationsRegistered = false;\n\n/**\n * Register custom JSON Logic operations for Rebase.\n * Call this once at app initialization.\n */\nexport function registerConditionOperations(): void {\n if (operationsRegistered) return;\n\n // Check if user has a specific role by ID\n jsonLogic.add_operation(\"hasRole\", function (this: ConditionContext, roleId: string) {\n return this?.user?.roles?.includes(roleId) ?? false;\n });\n\n // Check if user has any of the specified roles\n jsonLogic.add_operation(\"hasAnyRole\", function (this: ConditionContext, roleIds: string[]) {\n if (!this?.user?.roles || !Array.isArray(roleIds)) return false;\n return roleIds.some(role => this.user.roles.includes(role));\n });\n\n // Check if a timestamp is today\n jsonLogic.add_operation(\"isToday\", (timestamp: number) => {\n if (!timestamp) return false;\n const date = new Date(timestamp);\n const today = new Date();\n return date.getFullYear() === today.getFullYear() &&\n date.getMonth() === today.getMonth() &&\n date.getDate() === today.getDate();\n });\n\n // Check if a timestamp is in the past\n jsonLogic.add_operation(\"isPast\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp < Date.now();\n });\n\n // Check if a timestamp is in the future\n jsonLogic.add_operation(\"isFuture\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp > Date.now();\n });\n\n operationsRegistered = true;\n}\n\n/**\n * Evaluate a JSON Logic rule against the given context.\n */\nexport function evaluateCondition(rule: JsonLogicRule, context: ConditionContext): unknown {\n // Ensure operations are registered\n registerConditionOperations();\n return jsonLogic.apply(rule, context);\n}\n\n/**\n * Convert a value to a format suitable for JSON Logic evaluation.\n * Specifically handles Date objects by converting them to Unix timestamps.\n */\nfunction serializeValueForConditions(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n // Handle Date objects\n if (value instanceof Date) {\n return value.getTime();\n }\n\n // Handle Firestore Timestamp-like objects (have toDate or toMillis)\n if (typeof (value as { toMillis?: () => number })?.toMillis === \"function\") {\n return (value as { toMillis: () => number }).toMillis();\n }\n if (typeof (value as { toDate?: () => Date })?.toDate === \"function\") {\n return (value as { toDate: () => Date }).toDate().getTime();\n }\n\n // Handle arrays recursively\n if (Array.isArray(value)) {\n return value.map(serializeValueForConditions);\n }\n\n // Handle plain objects recursively\n if (typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = serializeValueForConditions((value as Record<string, unknown>)[key]);\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Build a ConditionContext from the current property resolution context.\n */\nexport function buildConditionContext(params: {\n propertyKey?: string;\n values?: Record<string, unknown>;\n previousValues?: Record<string, unknown>;\n path: string;\n entityId?: string;\n index?: number;\n authController: AuthState;\n}): ConditionContext {\n const {\n propertyKey,\n values,\n previousValues,\n path,\n entityId,\n index,\n authController\n } = params;\n\n const user = authController.user;\n const serializedValues = serializeValueForConditions(values ?? {});\n const serializedPreviousValues = serializeValueForConditions(previousValues ?? values ?? {});\n\n return {\n values: serializedValues as Record<string, unknown>,\n previousValues: serializedPreviousValues as Record<string, unknown>,\n propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : undefined,\n path,\n entityId,\n isNew: !entityId,\n index,\n user: {\n uid: user?.uid ?? \"\",\n email: user?.email ?? null,\n displayName: user?.displayName ?? null,\n photoURL: user?.photoURL ?? null,\n roles: (user?.roles ?? []).map((r: unknown) => typeof r === \"string\" ? r : (r as { id: string }).id)\n },\n now: Date.now()\n };\n}\n\n/**\n * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.\n */\n","const { getOwnPropertyNames, getOwnPropertySymbols } = Object;\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst { hasOwnProperty } = Object.prototype;\n/**\n * Combine two comparators into a single comparators.\n */\nfunction combineComparators(comparatorA, comparatorB) {\n return function isEqual(a, b, state) {\n return comparatorA(a, b, state) && comparatorB(a, b, state);\n };\n}\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nfunction createIsCircular(areItemsEqual) {\n return function isCircular(a, b, state) {\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n return areItemsEqual(a, b, state);\n }\n const { cache } = state;\n const cachedA = cache.get(a);\n const cachedB = cache.get(b);\n if (cachedA && cachedB) {\n return cachedA === b && cachedB === a;\n }\n cache.set(a, b);\n cache.set(b, a);\n const result = areItemsEqual(a, b, state);\n cache.delete(a);\n cache.delete(b);\n return result;\n };\n}\n/**\n * Get the properties to strictly examine, which include both own properties that are\n * not enumerable and symbol properties.\n */\nfunction getStrictProperties(object) {\n return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));\n}\n/**\n * Whether the object contains the property passed as an own property.\n */\nconst hasOwn = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.hasOwn || ((object, property) => hasOwnProperty.call(object, property));\n\nconst PREACT_VNODE = '__v';\nconst PREACT_OWNER = '__o';\nconst REACT_OWNER = '_owner';\nconst { getOwnPropertyDescriptor, keys } = Object;\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevalue) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`) or both are `NaN`.\n *\n * @note\n * When available in the environment, this is just a re-export of the global\n * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) method.\n */\nconst sameValueEqual = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.is\n || function sameValueEqual(a, b) {\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n };\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevaluezero) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`), both are `NaN`, or both\n * are either positive or negative zero.\n */\nfunction sameValueZeroEqual(a, b) {\n return a === b || (a !== a && b !== b);\n}\n/**\n * Whether the values passed are equal based on a\n * [Strict Equality Comparison](https://262.ecma-international.org/7.0/#sec-strict-equality-comparison) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`).\n *\n * @note\n * This is mainly available as a convenience function, such as being a default when a function to determine equality between\n * two objects is used.\n */\nfunction strictEqual(a, b) {\n return a === b;\n}\n/**\n * Whether the array buffers are equal in value.\n */\nfunction areArrayBuffersEqual(a, b) {\n return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b));\n}\n/**\n * Whether the arrays are equal in value.\n */\nfunction areArraysEqual(a, b, state) {\n let index = a.length;\n if (b.length !== index) {\n return false;\n }\n while (index-- > 0) {\n if (!state.equals(a[index], b[index], index, index, a, b, state)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the dataviews are equal in value.\n */\nfunction areDataViewsEqual(a, b) {\n return (a.byteLength === b.byteLength\n && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)));\n}\n/**\n * Whether the dates passed are equal in value.\n */\nfunction areDatesEqual(a, b) {\n return sameValueEqual(a.getTime(), b.getTime());\n}\n/**\n * Whether the errors passed are equal in value.\n */\nfunction areErrorsEqual(a, b) {\n return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack;\n}\n/**\n * Whether the `Map`s are equal in value.\n */\nfunction areMapsEqual(a, b, state) {\n const size = a.size;\n if (size !== b.size) {\n return false;\n }\n if (!size) {\n return true;\n }\n const matchedIndices = new Array(size);\n const aIterable = a.entries();\n let aResult;\n let bResult;\n let index = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n const bIterable = b.entries();\n let hasMatch = false;\n let matchIndex = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n if (matchedIndices[matchIndex]) {\n matchIndex++;\n continue;\n }\n const aEntry = aResult.value;\n const bEntry = bResult.value;\n if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state)\n && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n matchIndex++;\n }\n if (!hasMatch) {\n return false;\n }\n index++;\n }\n return true;\n}\n/**\n * Whether the objects are equal in value.\n */\nfunction areObjectsEqual(a, b, state) {\n const properties = keys(a);\n let index = properties.length;\n if (keys(b).length !== index) {\n return false;\n }\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n if (!isPropertyEqual(a, b, state, properties[index])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the objects are equal in value with strict property checking.\n */\nfunction areObjectsEqualStrict(a, b, state) {\n const properties = getStrictProperties(a);\n let index = properties.length;\n if (getStrictProperties(b).length !== index) {\n return false;\n }\n let property;\n let descriptorA;\n let descriptorB;\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n property = properties[index];\n if (!isPropertyEqual(a, b, state, property)) {\n return false;\n }\n descriptorA = getOwnPropertyDescriptor(a, property);\n descriptorB = getOwnPropertyDescriptor(b, property);\n if ((descriptorA || descriptorB)\n && (!descriptorA\n || !descriptorB\n || descriptorA.configurable !== descriptorB.configurable\n || descriptorA.enumerable !== descriptorB.enumerable\n || descriptorA.writable !== descriptorB.writable)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the primitive wrappers passed are equal in value.\n */\nfunction arePrimitiveWrappersEqual(a, b) {\n return sameValueEqual(a.valueOf(), b.valueOf());\n}\n/**\n * Whether the regexps passed are equal in value.\n */\nfunction areRegExpsEqual(a, b) {\n return a.source === b.source && a.flags === b.flags;\n}\n/**\n * Whether the `Set`s are equal in value.\n */\nfunction areSetsEqual(a, b, state) {\n const size = a.size;\n if (size !== b.size) {\n return false;\n }\n if (!size) {\n return true;\n }\n const matchedIndices = new Array(size);\n const aIterable = a.values();\n let aResult;\n let bResult;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n const bIterable = b.values();\n let hasMatch = false;\n let matchIndex = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n if (!matchedIndices[matchIndex]\n && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n matchIndex++;\n }\n if (!hasMatch) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the TypedArray instances are equal in value.\n */\nfunction areTypedArraysEqual(a, b) {\n let index = a.byteLength;\n if (b.byteLength !== index || a.byteOffset !== b.byteOffset) {\n return false;\n }\n while (index-- > 0) {\n if (a[index] !== b[index]) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the URL instances are equal in value.\n */\nfunction areUrlsEqual(a, b) {\n return (a.hostname === b.hostname\n && a.pathname === b.pathname\n && a.protocol === b.protocol\n && a.port === b.port\n && a.hash === b.hash\n && a.username === b.username\n && a.password === b.password);\n}\nfunction isPropertyEqual(a, b, state, property) {\n if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE)\n && (a.$$typeof || b.$$typeof)) {\n return true;\n }\n return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state);\n}\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n/**\n * Create a comparator method based on the type-specific equality comparators passed.\n */\nfunction createEqualityComparator(config) {\n const supportedComparatorMap = createSupportedComparatorMap(config);\n const { areArraysEqual, areDatesEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, areRegExpsEqual, areSetsEqual, getUnsupportedCustomComparator, } = config;\n /**\n * compare the value of the two objects and return true if they are equivalent in values\n */\n return function comparator(a, b, state) {\n // If the items are strictly equal, no need to do a value comparison.\n if (a === b) {\n return true;\n }\n // If either of the items are nullish and fail the strictly equal check\n // above, then they must be unequal.\n if (a == null || b == null) {\n return false;\n }\n const type = typeof a;\n if (type !== typeof b) {\n return false;\n }\n if (type !== 'object') {\n if (type === 'number' || type === 'bigint') {\n return areNumbersEqual(a, b, state);\n }\n if (type === 'function') {\n return areFunctionsEqual(a, b, state);\n }\n // If a primitive value that is not strictly equal, it must be unequal.\n return false;\n }\n const constructor = a.constructor;\n // Checks are listed in order of commonality of use-case:\n // 1. Common complex object types (plain object, array)\n // 2. Common data values (date, regexp)\n // 3. Less-common complex object types (map, set)\n // 4. Less-common data values (promise, primitive wrappers)\n // Inherently this is both subjective and assumptive, however\n // when reviewing comparable libraries in the wild this order\n // appears to be generally consistent.\n // Constructors should match, otherwise there is potential for false positives\n // between class and subclass or custom object and POJO.\n if (constructor !== b.constructor) {\n return false;\n }\n // Try to fast-path equality checks for other complex object types in the\n // same realm to avoid capturing the string tag. Strict equality is used\n // instead of `instanceof` because it is more performant for the common\n // use-case. If someone is creating a subclass from a native class, it will be\n // handled with the string tag comparison.\n if (constructor === Object) {\n return areObjectsEqual(a, b, state);\n }\n if (constructor === Array) {\n return areArraysEqual(a, b, state);\n }\n if (constructor === Date) {\n return areDatesEqual(a, b, state);\n }\n if (constructor === RegExp) {\n return areRegExpsEqual(a, b, state);\n }\n if (constructor === Map) {\n return areMapsEqual(a, b, state);\n }\n if (constructor === Set) {\n return areSetsEqual(a, b, state);\n }\n if (constructor === Promise) {\n // Avoid tag checks for promise values, since we know if they are not referentially equal\n // then they are not equal.\n return false;\n }\n // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing\n // the string tag or doing an `instanceof` in edge cases.\n if (Array.isArray(a)) {\n return areArraysEqual(a, b, state);\n }\n // Since this is a custom object, capture the string tag to determining its type.\n // This is reasonably performant in modern environments like v8 and SpiderMonkey.\n const tag = toString.call(a);\n const supportedComparator = supportedComparatorMap[tag];\n if (supportedComparator) {\n return supportedComparator(a, b, state);\n }\n const unsupportedCustomComparator = getUnsupportedCustomComparator && getUnsupportedCustomComparator(a, b, state, tag);\n if (unsupportedCustomComparator) {\n return unsupportedCustomComparator(a, b, state);\n }\n // If not matching any tags that require a specific type of comparison, then we hard-code false because\n // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\n // - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\n // comparison that can be made.\n // - For types that can be introspected but do not have an objective definition of what\n // equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\n // In all cases, these decisions should be reevaluated based on changes to the language and\n // common development practices.\n return false;\n };\n}\n/**\n * Create the configuration object used for building comparators.\n */\nfunction createEqualityComparatorConfig({ circular, createCustomConfig, strict, }) {\n let config = {\n areArrayBuffersEqual,\n areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,\n areDataViewsEqual,\n areDatesEqual: areDatesEqual,\n areErrorsEqual: areErrorsEqual,\n areFunctionsEqual: strictEqual,\n areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual,\n areNumbersEqual: sameValueEqual,\n areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,\n arePrimitiveWrappersEqual: arePrimitiveWrappersEqual,\n areRegExpsEqual: areRegExpsEqual,\n areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual,\n areTypedArraysEqual: strict\n ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict)\n : areTypedArraysEqual,\n areUrlsEqual: areUrlsEqual,\n getUnsupportedCustomComparator: undefined,\n };\n if (createCustomConfig) {\n config = Object.assign({}, config, createCustomConfig(config));\n }\n if (circular) {\n const areArraysEqual = createIsCircular(config.areArraysEqual);\n const areMapsEqual = createIsCircular(config.areMapsEqual);\n const areObjectsEqual = createIsCircular(config.areObjectsEqual);\n const areSetsEqual = createIsCircular(config.areSetsEqual);\n config = Object.assign({}, config, {\n areArraysEqual,\n areMapsEqual,\n areObjectsEqual,\n areSetsEqual,\n });\n }\n return config;\n}\n/**\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\n * use inside the built comparator.\n */\nfunction createInternalEqualityComparator(compare) {\n return function (a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) {\n return compare(a, b, state);\n };\n}\n/**\n * Create the `isEqual` function used by the consuming application.\n */\nfunction createIsEqual({ circular, comparator, createState, equals, strict }) {\n if (createState) {\n return function isEqual(a, b) {\n const { cache = circular ? new WeakMap() : undefined, meta } = createState();\n return comparator(a, b, {\n cache,\n equals,\n meta,\n strict,\n });\n };\n }\n if (circular) {\n return function isEqual(a, b) {\n return comparator(a, b, {\n cache: new WeakMap(),\n equals,\n meta: undefined,\n strict,\n });\n };\n }\n const state = {\n cache: undefined,\n equals,\n meta: undefined,\n strict,\n };\n return function isEqual(a, b) {\n return comparator(a, b, state);\n };\n}\n/**\n * Create a map of `toString()` values to their respective handlers for `tag`-based lookups.\n */\nfunction createSupportedComparatorMap({ areArrayBuffersEqual, areArraysEqual, areDataViewsEqual, areDatesEqual, areErrorsEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, arePrimitiveWrappersEqual, areRegExpsEqual, areSetsEqual, areTypedArraysEqual, areUrlsEqual, }) {\n return {\n '[object Arguments]': areObjectsEqual,\n '[object Array]': areArraysEqual,\n '[object ArrayBuffer]': areArrayBuffersEqual,\n '[object AsyncGeneratorFunction]': areFunctionsEqual,\n '[object BigInt]': areNumbersEqual,\n '[object BigInt64Array]': areTypedArraysEqual,\n '[object BigUint64Array]': areTypedArraysEqual,\n '[object Boolean]': arePrimitiveWrappersEqual,\n '[object DataView]': areDataViewsEqual,\n '[object Date]': areDatesEqual,\n // If an error tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n '[object Error]': areErrorsEqual,\n '[object Float16Array]': areTypedArraysEqual,\n '[object Float32Array]': areTypedArraysEqual,\n '[object Float64Array]': areTypedArraysEqual,\n '[object Function]': areFunctionsEqual,\n '[object GeneratorFunction]': areFunctionsEqual,\n '[object Int8Array]': areTypedArraysEqual,\n '[object Int16Array]': areTypedArraysEqual,\n '[object Int32Array]': areTypedArraysEqual,\n '[object Map]': areMapsEqual,\n '[object Number]': arePrimitiveWrappersEqual,\n '[object Object]': (a, b, state) => \n // The exception for value comparison is custom `Promise`-like class instances. These should\n // be treated the same as standard `Promise` objects, which means strict equality, and if\n // it reaches this point then that strict equality comparison has already failed.\n typeof a.then !== 'function' && typeof b.then !== 'function' && areObjectsEqual(a, b, state),\n // For RegExp, the properties are not enumerable, and therefore will give false positives if\n // tested like a standard object.\n '[object RegExp]': areRegExpsEqual,\n '[object Set]': areSetsEqual,\n '[object String]': arePrimitiveWrappersEqual,\n '[object URL]': areUrlsEqual,\n '[object Uint8Array]': areTypedArraysEqual,\n '[object Uint8ClampedArray]': areTypedArraysEqual,\n '[object Uint16Array]': areTypedArraysEqual,\n '[object Uint32Array]': areTypedArraysEqual,\n };\n}\n\n/**\n * Whether the items passed are deeply-equal in value.\n */\nconst deepEqual = createCustomEqual();\n/**\n * Whether the items passed are deeply-equal in value based on strict comparison.\n */\nconst strictDeepEqual = createCustomEqual({ strict: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references.\n */\nconst circularDeepEqual = createCustomEqual({ circular: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularDeepEqual = createCustomEqual({\n circular: true,\n strict: true,\n});\n/**\n * Whether the items passed are shallowly-equal in value.\n */\nconst shallowEqual = createCustomEqual({\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value based on strict comparison\n */\nconst strictShallowEqual = createCustomEqual({\n strict: true,\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references.\n */\nconst circularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueEqual,\n strict: true,\n});\n/**\n * Create a custom equality comparison method.\n *\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\n * where the standard methods are not performant enough, but can also be used to provide\n * support for legacy environments that do not support expected features like\n * `RegExp.prototype.flags` out of the box.\n */\nfunction createCustomEqual(options = {}) {\n const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false, } = options;\n const config = createEqualityComparatorConfig(options);\n const comparator = createEqualityComparator(config);\n const equals = createCustomInternalComparator\n ? createCustomInternalComparator(comparator)\n : createInternalEqualityComparator(comparator);\n return createIsEqual({ circular, comparator, createState, equals, strict });\n}\n\nexport { circularDeepEqual, circularShallowEqual, createCustomEqual, deepEqual, sameValueEqual, sameValueZeroEqual, shallowEqual, strictCircularDeepEqual, strictCircularShallowEqual, strictDeepEqual, strictEqual, strictShallowEqual };\n","import {\n DataSourceDefinition,\n ResolvedDataSource,\n DEFAULT_DATA_SOURCE_KEY,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\n\n/**\n * The subset of a collection needed to resolve its data source. Accepting a\n * structural type (rather than the full `CollectionConfig`) keeps this usable\n * from anywhere — frontend router, backend registry, editor — without coupling\n * to the collection union.\n */\nexport interface DataSourceResolvable {\n /** Preferred routing key. */\n dataSource?: string;\n /** Engine type discriminant (set on variant collection types). */\n engine?: string;\n /** Within-engine instance. */\n databaseId?: string;\n}\n\n/** A lookup of data-source definitions by key. */\nexport type DataSourceRegistry = Record<string, DataSourceDefinition>;\n\n/**\n * Build a keyed registry from a list of {@link DataSourceDefinition}s.\n * Later entries win on key collision.\n */\nexport function createDataSourceRegistry(definitions?: DataSourceDefinition[]): DataSourceRegistry {\n const registry: DataSourceRegistry = {};\n for (const def of definitions ?? []) {\n registry[def.key] = def;\n }\n return registry;\n}\n\n/**\n * Resolve the effective data source for a collection — the single source of\n * truth shared by the frontend router, the backend driver registry, and the\n * editor's capability lookups.\n *\n * Resolution order:\n * 1. The routing **key** is `collection.dataSource`, else\n * {@link DEFAULT_DATA_SOURCE_KEY}.\n * 2. If a definition is registered for that key, it provides `engine`,\n * `transport`, and `databaseId`.\n * 3. Otherwise values are synthesized: `engine` from `collection.engine`\n * (or the key, or `\"postgres\"`), `transport` defaults to `\"server\"`,\n * and `databaseId` from the collection.\n *\n * `capabilities` are always derived from the resolved `engine`, so two\n * data sources sharing an engine share capabilities.\n *\n * @param collection the collection (or any object carrying the routing fields)\n * @param registry optional registry of declared data sources\n */\nexport function resolveDataSource(\n collection: DataSourceResolvable | undefined,\n registry?: DataSourceRegistry\n): ResolvedDataSource {\n const key = collection?.dataSource ?? DEFAULT_DATA_SOURCE_KEY;\n const def = registry?.[key];\n\n const engine = def?.engine\n ?? collection?.engine\n ?? (key !== DEFAULT_DATA_SOURCE_KEY ? key : \"postgres\");\n\n const transport = def?.transport ?? \"server\";\n const databaseId = collection?.databaseId ?? def?.databaseId;\n\n return {\n key,\n engine,\n transport,\n databaseId,\n capabilities: getDataSourceCapabilities(engine)\n };\n}\n","import {\n ArrayProperty,\n CollectionCallbacks,\n EngineProperties,\n CollectionConfig,\n getDataSourceCapabilities,\n getDeclaredSubcollections,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty\n} from \"@rebasepro/types\";\nimport { deepEqual } from \"fast-equals\";\n\nimport {\n enumToObjectEntries,\n findRelation,\n getSubcollections,\n getTableName,\n resolveCollectionRelations,\n resolveRelation\n} from \"../util\";\nimport { deepClone, mergeDeep, removeFunctions } from \"@rebasepro/utils\";\nimport { DataSourceRegistry, resolveDataSource } from \"../data/resolveDataSource\";\n\nexport class CollectionRegistry {\n\n /**\n * Declared data sources, used during normalization to resolve each\n * collection's engine (so `dataSource`-only collections get the right\n * capabilities). Empty by default.\n */\n private dataSources: DataSourceRegistry = {};\n\n /**\n * Global lifecycle callbacks applied to every collection.\n * Runs on all data paths (REST, WebSocket, `rebase.data`).\n * Execution order: global → collection → property callbacks.\n */\n private _globalCallbacks?: CollectionCallbacks;\n\n /**\n * Set global lifecycle callbacks that apply to every collection.\n * Typically called once during backend initialization.\n */\n setGlobalCallbacks(callbacks: CollectionCallbacks): void {\n this._globalCallbacks = callbacks;\n }\n\n /**\n * Get the currently registered global callbacks, if any.\n */\n getGlobalCallbacks(): CollectionCallbacks | undefined {\n return this._globalCallbacks;\n }\n\n // Normalized runtime layer (used by Data Grid / UI)\n private collectionsByTableName = new Map<string, CollectionConfig>();\n private collectionsBySlug = new Map<string, CollectionConfig>();\n private rootCollections: CollectionConfig[] = [];\n private cachedCollectionsList: CollectionConfig[] | null = null;\n\n // Raw configuration layer (used by Collection Editor AST generator)\n private rawCollectionsByTableName = new Map<string, CollectionConfig>();\n private rawCollectionsBySlug = new Map<string, CollectionConfig>();\n private rawRootCollections: CollectionConfig[] = [];\n private cachedRawCollectionsList: CollectionConfig[] | null = null;\n\n // Entity of raw input for idempotency check — compared BEFORE normalization\n // to avoid the issue where normalization creates new objects that always fail equality.\n private lastRawInputEntity: ReturnType<typeof removeFunctions>[] | null = null;\n\n constructor(collections?: CollectionConfig[], dataSources?: DataSourceRegistry) {\n if (dataSources) this.dataSources = dataSources;\n if (collections) {\n this.registerMultiple(collections);\n }\n }\n\n /**\n * Provide the declared data sources used to resolve each collection's\n * engine during normalization. Set this before registering collections.\n * Returns true if the registry changed (callers may re-register).\n */\n setDataSources(dataSources: DataSourceRegistry): boolean {\n if (deepEqual(this.dataSources, dataSources)) return false;\n this.dataSources = dataSources ?? {};\n return true;\n }\n\n reset() {\n this.collectionsByTableName.clear();\n this.collectionsBySlug.clear();\n this.rootCollections = [];\n this.cachedCollectionsList = null;\n\n this.rawCollectionsByTableName.clear();\n this.rawCollectionsBySlug.clear();\n this.rawRootCollections = [];\n this.cachedRawCollectionsList = null;\n }\n\n /**\n * Registers a collection and its subcollections recursively.\n * Returns true if the collections have changed, false otherwise.\n *\n * Idempotent: compares the raw input (before normalization) against a stored\n * entity. Only re-normalizes and re-registers when the raw input actually changed.\n * @param collections\n */\n registerMultiple(collections: CollectionConfig[]): boolean {\n // Compare raw input BEFORE normalization to detect actual changes.\n // This avoids the old issue where normalization creates new objects\n // that always fail deep-equal even when the source data is identical.\n const rawEntity = collections.map(c => removeFunctions(c));\n if (this.lastRawInputEntity && deepEqual(this.lastRawInputEntity, rawEntity)) {\n return false;\n }\n\n this.reset();\n // Phase 0: Populate maps with raw collections first for string target resolution\n collections.forEach((c) => {\n if (c.slug) {\n this.collectionsBySlug.set(c.slug, c);\n }\n this.collectionsByTableName.set(getTableName(c), c);\n });\n\n const normalizedCollections = collections.map(c => this.normalizeCollection({ ...c }));\n\n // Phase 1: Register all top-level collections first (without recursion).\n // This ensures that injected entityViews (e.g. History tab) are preserved.\n // Without this, _registerRecursively could register a relation-target collection\n // (e.g. Tags from Posts.relations) using the raw module object (without injected views)\n // before the top-level Tags collection (with injected views) gets its turn.\n normalizedCollections.forEach((c, index) => {\n const raw = deepClone(collections[index]);\n this.rootCollections.push(c);\n this.rawRootCollections.push(raw);\n\n const normalized = this.normalizeCollection(c);\n this.collectionsByTableName.set(getTableName(normalized), normalized);\n this.rawCollectionsByTableName.set(getTableName(raw), raw);\n if (normalized.slug) {\n this.collectionsBySlug.set(normalized.slug, normalized);\n }\n if (raw.slug) {\n this.rawCollectionsBySlug.set(raw.slug, raw);\n }\n });\n\n // Phase 2: Now recurse into subcollections (relations, etc.)\n normalizedCollections.forEach((c) => {\n const subcollections = getSubcollections(c);\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n });\n\n // Store the entity for future comparisons\n this.lastRawInputEntity = rawEntity;\n\n return true;\n }\n\n register(collection: CollectionConfig, rawCollection?: CollectionConfig) {\n const raw = rawCollection ? deepClone(rawCollection) : deepClone(collection);\n\n this.rootCollections.push(collection);\n this.rawRootCollections.push(raw);\n\n this._registerRecursively(collection, raw);\n }\n\n private _registerRecursively(collection: CollectionConfig, rawCollection: CollectionConfig) {\n if (this.collectionsByTableName.has(getTableName(collection))) {\n return;\n }\n\n const normalizedCollection = this.normalizeCollection(collection);\n this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);\n this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);\n\n if (normalizedCollection.slug) {\n this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);\n }\n if (rawCollection.slug) {\n this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);\n }\n\n // Use the normalized collection for subcollection discovery so that\n // both inline-extracted and explicit relations are considered.\n const subcollections = getSubcollections(normalizedCollection);\n\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n }\n\n public normalizeCollection(collection: CollectionConfig): CollectionConfig {\n // Work on a shallow copy to avoid mutating the caller's reference.\n // This is critical for idempotency (the raw input must not be changed)\n // and for preventing mutation of module-level collection singletons.\n const result = { ...collection } as CollectionConfig;\n\n // 0. Resolve and stamp `dataSource` and `engine` on the normalized copy.\n // After this block every normalized collection has both fields set,\n // so downstream code can read them directly without calling\n // `resolveDataSource()`. Only the normalized layer is affected —\n // the raw layer used by the collection editor keeps the author's\n // original fields.\n {\n const resolved = resolveDataSource(result, this.dataSources);\n if (!result.dataSource) (result as { dataSource?: string }).dataSource = resolved.key;\n if (!result.engine) (result as { engine?: string }).engine = resolved.engine;\n }\n\n // Relations are left exactly as authored.\n //\n // This used to hoist every inline relation property into\n // `collection.relations`, merge it with the declared ones, and run each\n // through `sanitizeRelation` — a pass that guessed at missing fields and\n // fell back to the raw relation when it threw. `resolveCollectionRelations`\n // now reads both sources itself and defaults deterministically, so there\n // is nothing to hoist, nothing to merge and nothing to guess.\n //\n // The hoisting also had a defect worth not reinstating: it flattened\n // relations declared inside a `map` up to the collection's top level,\n // where they became child-view tabs keyed by the inner property key.\n\n // Stamp each relation property with its resolved relation.\n const properties: Properties = this.normalizeProperties(result.properties, result);\n result.properties = properties as EngineProperties;\n\n // `childCollections` is deliberately NOT populated here.\n //\n // It used to be, from the same many-relations `getEntityChildViews`\n // reads — but stamped with the *target's* slug rather than the relation\n // key, and then cached onto the collection, so the registry's version\n // shadowed the correct one for every consumer downstream. Deriving on\n // read leaves one implementation and keeps `childCollections` meaning\n // what it documents: a custom driver's explicit override.\n return result;\n }\n\n private normalizeProperties(properties: Properties, collection: CollectionConfig): Properties {\n const newProperties: Properties = {};\n for (const key in properties) {\n newProperties[key] = this.normalizeProperty(key, properties[key], collection);\n }\n return newProperties;\n }\n\n private normalizeProperty(key: string, property: Property, collection: CollectionConfig): Property {\n const newProperty = { ...property };\n\n if (newProperty.type === \"map\" && newProperty.properties) {\n newProperty.properties = this.normalizeProperties(newProperty.properties, collection);\n } else if (newProperty.type === \"array\") {\n // Cast to get a properly typed mutable reference\n const arrayProp = newProperty as ArrayProperty;\n if (arrayProp.of) {\n if (Array.isArray(arrayProp.of)) {\n (arrayProp as { of: Property | Property[] }).of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, collection));\n } else {\n arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, collection);\n }\n } else if (arrayProp.oneOf && arrayProp.oneOf.properties) {\n arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, collection);\n }\n } else if ((newProperty.type === \"string\" || newProperty.type === \"number\") && newProperty.enum) {\n const stringOrNumberProperty = newProperty as StringProperty | NumberProperty;\n if (typeof stringOrNumberProperty.enum === \"object\" && !Array.isArray(stringOrNumberProperty.enum)) {\n stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];\n }\n } else if (newProperty.type === \"relation\") {\n const relationProperty = newProperty as RelationProperty;\n\n // A property either declares its link inline, or names one the\n // collection declares. Resolve the first directly; look the second\n // up by name. Either way the property carries the fully-defaulted\n // relation, so no consumer has to re-derive it.\n if (relationProperty.relation) {\n relationProperty.resolvedRelation = resolveRelation(relationProperty.relation, collection, key);\n } else {\n const declared = resolveCollectionRelations(collection)[key];\n if (declared) {\n relationProperty.resolvedRelation = declared;\n } else {\n console.warn(\n `Relation property '${key}' on '${collection.slug}' declares no \\`relation\\`, and the ` +\n \"collection has no relation of that name.\"\n );\n }\n }\n }\n\n return newProperty;\n }\n\n get(path: string): CollectionConfig | undefined {\n // First try slug lookup\n const bySlug = this.collectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.collectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n // Fallback to table name lookup\n return this.collectionsByTableName.get(path);\n }\n\n /**\n * Gets the pristine, un-normalized collection exactly as it was provided.\n * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.\n */\n getRaw(path: string): CollectionConfig | undefined {\n const bySlug = this.rawCollectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.rawCollectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n return this.rawCollectionsByTableName.get(path);\n }\n\n /**\n * Get collection by resolving multi-segment paths through relations\n * e.g., \"authors/70/posts\" resolves to the posts collection\n */\n getCollectionByPath(collectionPath: string): CollectionConfig | undefined {\n // Handle simple single collection path\n if (!collectionPath.includes(\"/\")) {\n return this.get(collectionPath);\n }\n\n // Handle multi-segment paths by resolving through relations\n const pathSegments = collectionPath.split(\"/\").filter(p => p);\n\n if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {\n throw new Error(`Invalid relation path: ${collectionPath}. Expected format: collection/id/relation or collection/id/relation/id/relation`);\n }\n\n // Start with the root collection\n const rootCollectionPath = pathSegments[0];\n let currentCollection = this.get(rootCollectionPath);\n\n if (!currentCollection) {\n throw new Error(`Root collection not found: ${rootCollectionPath}`);\n }\n\n // Navigate through the path using relations\n for (let i = 2; i < pathSegments.length; i += 2) {\n const relationKey = pathSegments[i];\n\n // Get relations for current collection\n if (!getDataSourceCapabilities(currentCollection.engine).supportsRelations) {\n throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses engine '${currentCollection.engine}'`);\n }\n const resolvedRelations = resolveCollectionRelations(currentCollection);\n const relation = findRelation(resolvedRelations, relationKey);\n\n if (!relation) {\n throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);\n }\n\n // Move to the target collection.\n //\n // By the relation's own target, never by a slug lookup on its\n // *name*: `this.get(relation.relationName)` searches the global slug\n // map, so a relation named `people` that targets `notes` resolved to\n // an unrelated root collection called `people` — and a nested write\n // then ran that collection's callbacks against its properties.\n // The registered instance is preferred, matched by table, to pick up\n // whatever normalization and injection it received.\n const target = relation.target();\n currentCollection = this.collectionsByTableName.get(getTableName(target))\n ?? this.normalizeCollection(target);\n\n // If there are more segments, continue navigation\n if (i + 1 < pathSegments.length) {\n // Skip entity ID segment\n }\n }\n\n return currentCollection;\n }\n\n getCollections(): CollectionConfig[] {\n if (!this.cachedCollectionsList) {\n this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());\n }\n return this.cachedCollectionsList;\n }\n\n getRawCollections(): CollectionConfig[] {\n if (!this.cachedRawCollectionsList) {\n this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());\n }\n return this.cachedRawCollectionsList;\n }\n\n /**\n * Resolves a multi-segment path like \"products/123/locales\" and returns\n * information about the collections and entity IDs along the path\n */\n resolvePathToCollections(path: string): {\n collections: CollectionConfig[],\n entityIds: (string | number)[],\n finalCollection: CollectionConfig\n } {\n const pathSegments = path.split(\"/\").filter(p => p);\n\n if (pathSegments.length === 0) {\n throw new Error(`Invalid path: ${path}`);\n }\n\n if (pathSegments.length % 2 !== 1) {\n throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);\n }\n\n const collections: CollectionConfig[] = [];\n const entityIds: (string | number)[] = [];\n\n // Start with the first collection\n let currentCollection = this.get(pathSegments[0]);\n\n if (!currentCollection) {\n throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);\n }\n\n collections.push(currentCollection);\n\n // Process the rest of the path in pairs (entityId, subcollectionSlug)\n for (let i = 1; i < pathSegments.length; i += 2) {\n const entityId = pathSegments[i];\n entityIds.push(entityId);\n\n if (i + 1 < pathSegments.length) {\n const subcollectionSlug = pathSegments[i + 1];\n const subcollections: CollectionConfig[] | undefined = getSubcollections(currentCollection);\n if (!subcollections || subcollections.length === 0) {\n throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);\n }\n\n const subcollection: CollectionConfig | undefined = subcollections.find(c => c.slug === subcollectionSlug);\n if (!subcollection) {\n throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);\n }\n // The child as resolved, not whatever root collection happens to\n // share its slug. Re-looking it up globally both risked the wrong\n // collection and discarded the relation's `overrides`, which are\n // applied when the child view is built.\n currentCollection = this.normalizeCollection(subcollection);\n collections.push(currentCollection);\n }\n }\n\n return {\n collections,\n entityIds,\n finalCollection: currentCollection\n };\n }\n\n}\n\n","import { defineCollection } from \"../util/builders\";\n\n/**\n * Default users collection.\n *\n * Prepended to the developer's collections array by the admin and server.\n * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers\n * override by defining their own collection with `slug: \"users\"`.\n *\n * Schema only — no `admin` block. This package is on the backend's dependency path,\n * where that field does not exist: `@rebasepro/admin-types` adds it by declaration\n * merging, and a BaaS install never installs that. The scaffolded\n * `config/collections/users.ts` carries the presentation for projects that want this\n * collection in their panel, which is also where it is editable.\n */\nexport const defaultUsersCollection = defineCollection({\n name: \"Users\",\n singularName: \"User\",\n slug: \"users\",\n auth: true,\n table: \"users\",\n schema: \"rebase\",\n securityRules: [\n { operation: \"select\",\nroles: [\"admin\"] },\n { operations: [\"insert\", \"update\", \"delete\"],\nroles: [\"admin\"] }\n ],\n properties: {\n id: {\n name: \"ID\",\n type: \"string\",\n isId: \"uuid\"\n },\n email: {\n name: \"Email\",\n type: \"string\",\n validation: { required: true,\nunique: true }\n },\n displayName: {\n name: \"Name\",\n type: \"string\",\n columnName: \"display_name\",\n validation: { required: true }\n },\n photoURL: {\n name: \"Photo URL\",\n type: \"string\",\n columnName: \"photo_url\"\n },\n roles: {\n name: \"Roles\",\n type: \"array\",\n columnType: \"text[]\",\n of: {\n name: \"Role\",\n type: \"string\",\n enum: {\n admin: \"Admin\",\n editor: \"Editor\",\n viewer: \"Viewer\"\n }\n }\n },\n passwordHash: {\n name: \"Password Hash\",\n type: \"string\",\n columnName: \"password_hash\",\n excludeFromApi: true\n },\n emailVerified: {\n name: \"Email Verified\",\n type: \"boolean\",\n columnName: \"email_verified\",\n defaultValue: false\n },\n emailVerificationToken: {\n name: \"Email Verification Token\",\n type: \"string\",\n columnName: \"email_verification_token\",\n excludeFromApi: true\n },\n emailVerificationSentAt: {\n name: \"Email Verification Sent At\",\n type: \"date\",\n columnName: \"email_verification_sent_at\"\n },\n metadata: {\n name: \"Metadata\",\n type: \"map\",\n keyValue: true,\n properties: {},\n defaultValue: {}\n },\n createdAt: {\n name: \"Created At\",\n type: \"date\",\n columnName: \"created_at\",\n autoValue: \"on_create\"\n },\n updatedAt: {\n name: \"Updated At\",\n type: \"date\",\n columnName: \"updated_at\",\n autoValue: \"on_update\"\n }\n }\n});\n","import {\n CollectionAccessor,\n FilterCondition,\n FindParams,\n FindResponse,\n LogicalCondition,\n QueryBuilderInterface,\n WhereFilterOp,\n WhereValue\n} from \"@rebasepro/types\";\n\nexport function or(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"or\",\nconditions };\n}\n\nexport function and(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"and\",\nconditions };\n}\n\nexport function cond(column: string, operator: WhereFilterOp, value: unknown): FilterCondition {\n return { column,\noperator,\nvalue };\n}\n\nexport class QueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements QueryBuilderInterface<M> {\n // Keyed by plain `string` on purpose: it is written in place by the\n // methods below, whose own parameters are typed against `M`, and a\n // `Partial<Record<FieldPath<M>, …>>` is read-only under a generic `M`\n // (TS2862). The typing users see is on the methods; this is the buffer\n // behind them, cast once at each handoff.\n private params: FindParams = { where: {} };\n\n constructor(private collection: CollectionAccessor<M>) {}\n\n /**\n * Add a filter condition to your query.\n * @example\n * client.collection('users').where('age', '>=', 18).find()\n */\n where<K extends keyof M & string>(column: K, operator: WhereFilterOp, value: WhereValue<M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown): this {\n // Handle LogicalCondition signature\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n this.params.logical = columnOrCondition as LogicalCondition;\n return this;\n }\n\n if (!this.params.where) {\n this.params.where = {};\n }\n\n const column = columnOrCondition as string;\n const condition: [WhereFilterOp, unknown] = [operator!, value];\n const existing = this.params.where[column];\n\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [WhereFilterOp, unknown][]).push(condition);\n } else {\n // Convert existing single tuple/value into array of tuples\n let firstCondition: [WhereFilterOp, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [WhereFilterOp, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n\n return this;\n }\n\n /**\n * Order the results by a specific column.\n * @example\n * client.collection('users').orderBy('createdAt', 'desc').find()\n */\n orderBy(column: keyof M & string, direction: \"asc\" | \"desc\" = \"asc\"): this {\n this.params.orderBy = [column, direction];\n return this;\n }\n\n /**\n * Limit the number of results returned.\n */\n limit(count: number): this {\n this.params.limit = count;\n return this;\n }\n\n /**\n * Skip the first N results.\n */\n offset(count: number): this {\n this.params.offset = count;\n return this;\n }\n\n /**\n * Set a free-text search string if supported by the backend.\n */\n search(searchString: string): this {\n this.params.searchString = searchString;\n return this;\n }\n\n /**\n * Include related entities in the response.\n * Relations will be populated with full entity data instead of just IDs.\n *\n * @param relations - Relation names to include, or \"*\" for all.\n * @example\n * // Include specific relations\n * client.data.posts.include(\"tags\", \"author\").find()\n *\n * // Include all relations\n * client.data.posts.include(\"*\").find()\n */\n include(...relations: string[]): this {\n this.params.include = relations;\n return this;\n }\n\n /**\n * Execute the find query and return the results.\n */\n async find(): Promise<FindResponse<M>> {\n return this.collection.find(this.params as FindParams<M>) as Promise<FindResponse<M>>;\n }\n\n /**\n * Listen to realtime updates matching this query.\n */\n listen(onUpdate: (data: FindResponse<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.collection.listen) {\n throw new Error(\"Listen is only available when RebaseClient is configured with a websocketUrl.\");\n }\n return this.collection.listen(this.params as FindParams<M>, onUpdate, onError);\n }\n}\n","/**\n * REST wire-format adapter for the unified filter system.\n *\n * This module is the ONLY code in the entire codebase that knows about\n * PostgREST-style dot-syntax strings (`eq.active`, `gt.18`, `in.(a,b)`).\n * Everything else speaks `FilterValues` exclusively.\n *\n * Wire-format values are always strings — the wire format carries no type\n * metadata, so type coercion is the responsibility of the server-side data\n * driver which has access to the collection schema.\n *\n * Commas inside list values are backslash-escaped (`\\,`), and literal\n * backslashes are escaped as `\\\\`.\n *\n * @module\n */\n\nimport {\n WhereFilterOp,\n FilterValues,\n CANONICAL_TO_REST,\n REST_TO_CANONICAL,\n RestFilterOp,\n toCanonicalOp,\n LogicalCondition,\n FilterCondition,\n NULL_OPS\n} from \"@rebasepro/types\";\nimport { normalizeToEntityRelation } from \"../util/entities\";\n\n// ---------------------------------------------------------------------------\n// Value stringification\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a JS value to its querystring representation.\n * `null` is serialized as the literal string `\"null\"`.\n * Relation values (`EntityRelation` instances or `{ __type: \"relation\", id, path }`\n * objects) are serialized as their raw id — the wire format only carries the\n * value to compare against the FK column.\n */\nfunction stringifyValue(value: unknown): string {\n if (value === null) return \"null\";\n const relation = normalizeToEntityRelation(value);\n if (relation) return String(relation.id);\n return String(value);\n}\n\n// ---------------------------------------------------------------------------\n// Comma escaping for list values\n// ---------------------------------------------------------------------------\n\n/**\n * Escape a single list item for the wire format.\n * `\\` → `\\\\`, `,` → `\\,`\n */\nfunction escapeListItem(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/,/g, \"\\\\,\");\n}\n\n/**\n * Unescape a single list item from the wire format.\n * `\\\\` → `\\`, `\\,` → `,`\n */\nfunction unescapeListItem(value: string): string {\n let result = \"\";\n for (let i = 0; i < value.length; i++) {\n if (value[i] === \"\\\\\" && i + 1 < value.length) {\n result += value[i + 1];\n i++; // skip next char\n } else {\n result += value[i];\n }\n }\n return result;\n}\n\n/**\n * Split a parenthesized list string on unescaped commas.\n * Input is the content between `(` and `)`.\n *\n * @example\n * splitListItems(\"admin,editor\") // [\"admin\", \"editor\"]\n * splitListItems(\"hello\\\\, world,foo\") // [\"hello, world\", \"foo\"]\n */\nfunction splitListItems(inner: string): string[] {\n const items: string[] = [];\n let current = \"\";\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === \"\\\\\" && i + 1 < inner.length) {\n // Escaped character — consume both chars\n current += inner[i] + inner[i + 1];\n i++;\n } else if (inner[i] === \",\") {\n items.push(unescapeListItem(current));\n current = \"\";\n } else {\n current += inner[i];\n }\n }\n items.push(unescapeListItem(current));\n return items;\n}\n\n// ---------------------------------------------------------------------------\n// Typed operator map lookups (no `as any`)\n// ---------------------------------------------------------------------------\n\nconst REST_OP_LOOKUP = REST_TO_CANONICAL as Readonly<Record<string, WhereFilterOp | undefined>>;\nconst CANONICAL_OP_LOOKUP = CANONICAL_TO_REST as Readonly<Record<string, RestFilterOp | undefined>>;\n\n// ---------------------------------------------------------------------------\n// Serialize: FilterValues → REST querystring\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a single canonical condition tuple to a PostgREST dot-string.\n *\n * Throws `TypeError` if the input is not a valid `[WhereFilterOp, unknown]` tuple.\n *\n * @example\n * serializeTuple([\"==\", \"active\"]) // \"eq.active\"\n * serializeTuple([\"in\", [\"admin\",\"editor\"]]) // \"in.(admin,editor)\"\n * serializeTuple([\">=\", 18]) // \"gte.18\"\n */\nfunction serializeTuple(tuple: [WhereFilterOp, unknown]): string {\n if (!Array.isArray(tuple) || tuple.length !== 2) {\n throw new TypeError(\n `serializeTuple: expected a [WhereFilterOp, value] tuple, got ${JSON.stringify(tuple)}`\n );\n }\n\n const [op, value] = tuple;\n\n if (typeof op !== \"string\") {\n throw new TypeError(\n `serializeTuple: operator must be a string, got ${typeof op}`\n );\n }\n\n const restOp = CANONICAL_OP_LOOKUP[op];\n if (!restOp) {\n throw new TypeError(\n `serializeTuple: unknown operator \"${op}\". Valid operators: ${Object.keys(CANONICAL_TO_REST).join(\", \")}`\n );\n }\n\n if (Array.isArray(value)) {\n const items = value.map(v => escapeListItem(stringifyValue(v))).join(\",\");\n return `${restOp}.(${items})`;\n }\n\n return `${restOp}.${stringifyValue(value)}`;\n}\n\n/**\n * Convert `FilterValues` (or `WireFilterValues`) to a PostgREST-style\n * querystring record.\n *\n * - Canonical `[WhereFilterOp, value]` tuples are serialized strictly.\n * - Pre-serialized PostgREST strings (e.g. `\"eq.published\"`) are passed through.\n * - Single conditions produce a string value.\n * - Multiple conditions on the same field produce a string array (repeated params).\n *\n * @example\n * serializeFilter({ status: [\"==\", \"active\"] })\n * // → { status: \"eq.active\" }\n *\n * serializeFilter({ age: [[\">=\", 18], [\"<\", 65]] })\n * // → { age: [\"gte.18\", \"lt.65\"] }\n *\n * // Pre-serialized strings pass through unchanged:\n * serializeFilter({ status: \"eq.published\" })\n * // → { status: \"eq.published\" }\n */\nexport function serializeFilter(\n filter: FilterValues<string> | Record<string, unknown>\n): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n\n for (const [field, condition] of Object.entries(filter)) {\n if (condition === undefined) continue;\n\n // Pre-serialized PostgREST string — pass through unchanged.\n // This supports WireFilterValues where values may already be\n // serialized dot-strings like \"eq.active\" or raw strings like \"true\".\n if (typeof condition === \"string\") {\n result[field] = condition;\n continue;\n }\n\n // Multiple conditions on the same field: array of tuples\n // We detect this by checking if the first element is also an array.\n if (Array.isArray(condition) && condition.length > 0 && Array.isArray(condition[0])) {\n result[field] = (condition as [WhereFilterOp, unknown][]).map(serializeTuple);\n } else {\n // Single condition — must be a [WhereFilterOp, value] tuple\n result[field] = serializeTuple(condition as [WhereFilterOp, unknown]);\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Deserialize: REST querystring → FilterValues\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a single PostgREST dot-string into a `[WhereFilterOp, unknown]` tuple.\n *\n * All values are returned as strings — the wire format carries no type\n * metadata, so coercion is the data driver's responsibility.\n *\n * If the string doesn't match a known operator prefix, it falls back to\n * `[\"==\", originalString]` (treating the whole string as an equality value).\n * This intentional defense handles values like `\"user@host.com\"` or\n * `\"1.2.3\"` that happen to contain dots.\n */\nfunction deserializeSingle(raw: string): [WhereFilterOp, unknown] {\n const dotIndex = raw.indexOf(\".\");\n if (dotIndex === -1) {\n // No dot → equality on the raw value (kept as string)\n return [\"==\", raw];\n }\n\n const prefix = raw.substring(0, dotIndex);\n const rest = raw.substring(dotIndex + 1);\n\n // Check if the prefix is a known REST operator.\n // This is the key defense against values like \"eq.something\" or \"gt.foo\"\n // being misinterpreted — only known REST short-codes are treated as operators.\n const canonicalOp = REST_OP_LOOKUP[prefix];\n if (!canonicalOp) {\n // Not a known operator (e.g., email \"user@host.com\" or version \"1.2.3\")\n // Treat the entire string as an equality value\n return [\"==\", raw];\n }\n\n // Null-testing operators ignore their serialized value — normalize to null\n // so the tuple round-trips stably (`isnull.null` → [\"is-null\", null]).\n if (NULL_OPS.has(canonicalOp)) {\n return [canonicalOp, null];\n }\n\n // Parse list values: \"(admin,editor)\" → [\"admin\", \"editor\"]\n if (rest.startsWith(\"(\") && rest.endsWith(\")\")) {\n const items = splitListItems(rest.slice(1, -1));\n return [canonicalOp, items];\n }\n\n return [canonicalOp, rest];\n}\n\n/**\n * Convert a PostgREST-style querystring record to `FilterValues`.\n *\n * - String values are parsed as single conditions.\n * - String arrays (repeated query params) become multiple conditions on the same field.\n *\n * @example\n * deserializeFilter({ status: \"eq.active\" })\n * // → { status: [\"==\", \"active\"] }\n *\n * deserializeFilter({ age: [\"gte.18\", \"lt.65\"] })\n * // → { age: [[\">=\", \"18\"], [\"<\", \"65\"]] }\n */\nexport function deserializeFilter(\n query: Record<string, unknown>\n): FilterValues<string> {\n const result: FilterValues<string> = {};\n\n for (const [field, raw] of Object.entries(query)) {\n if (raw === undefined) continue;\n\n // If it's already a canonical tuple [op, value], keep it as is\n if (Array.isArray(raw) && raw.length === 2 && typeof raw[0] === \"string\" && toCanonicalOp(raw[0]) === raw[0]) {\n result[field] = raw as [WhereFilterOp, unknown];\n continue;\n }\n\n if (Array.isArray(raw)) {\n if (raw.length === 0) continue;\n \n // Check if it's an array of canonical tuples\n if (Array.isArray(raw[0]) && raw[0].length === 2 && typeof raw[0][0] === \"string\" && toCanonicalOp(raw[0][0]) === raw[0][0]) {\n result[field] = raw as [WhereFilterOp, unknown][];\n continue;\n }\n\n if (raw.length === 1) {\n result[field] = typeof raw[0] === \"string\" ? deserializeSingle(raw[0]) : [\"==\", raw[0]];\n } else {\n // If the elements are strings, they might be PostgREST dot-strings (repeated params)\n if (typeof raw[0] === \"string\" && raw[0].includes(\".\")) {\n result[field] = raw.map(r => typeof r === \"string\" ? deserializeSingle(r) : ([\"==\", r] as [WhereFilterOp, unknown])) as [WhereFilterOp, unknown][];\n } else {\n // Otherwise assume it's a list of values for an implicit \"in\" or just multiple conditions\n result[field] = [\"in\", raw];\n }\n }\n } else if (typeof raw === \"string\") {\n result[field] = deserializeSingle(raw);\n } else {\n result[field] = [\"==\", raw];\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Logical conditions: serialize / deserialize\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a `LogicalCondition` or `FilterCondition` to its wire-format string.\n *\n * @example\n * serializeLogicalCondition({ column: \"status\", operator: \"==\", value: \"active\" })\n * // → \"status.eq.active\"\n *\n * serializeLogicalCondition({ type: \"or\", conditions: [...] })\n * // → \"or(status.eq.active,status.eq.pending)\"\n */\nexport function serializeLogicalCondition(\n cond: LogicalCondition | FilterCondition\n): string {\n if (\"type\" in cond) {\n // LogicalCondition (and/or)\n const inner = (cond.conditions ?? [])\n .map(serializeLogicalCondition)\n .join(\",\");\n return `${cond.type}(${inner})`;\n }\n\n // FilterCondition\n const restOp = CANONICAL_OP_LOOKUP[cond.operator] ?? \"eq\";\n if (Array.isArray(cond.value)) {\n const items = cond.value.map(v => escapeListItem(stringifyValue(v))).join(\",\");\n return `${cond.column}.${restOp}.(${items})`;\n }\n return `${cond.column}.${restOp}.${stringifyValue(cond.value)}`;\n}\n\n/**\n * Parse a logical condition wire-format string back into a\n * `LogicalCondition` or `FilterCondition`.\n *\n * @example\n * deserializeLogicalCondition(\"status.eq.active\")\n * // → { column: \"status\", operator: \"==\", value: \"active\" }\n *\n * deserializeLogicalCondition(\"or(status.eq.active,age.gte.18)\")\n * // → { type: \"or\", conditions: [...] }\n */\nexport function deserializeLogicalCondition(\n str: string\n): LogicalCondition | FilterCondition {\n // Check for logical group: \"and(...)\" or \"or(...)\"\n const logicalMatch = str.match(/^(and|or)\\((.+)\\)$/);\n if (logicalMatch) {\n const type = logicalMatch[1] as \"and\" | \"or\";\n const innerStr = logicalMatch[2];\n\n // Split on commas that are not inside parentheses\n const conditions: (LogicalCondition | FilterCondition)[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < innerStr.length; i++) {\n if (innerStr[i] === \"(\") depth++;\n else if (innerStr[i] === \")\") depth--;\n else if (innerStr[i] === \",\" && depth === 0) {\n conditions.push(deserializeLogicalCondition(innerStr.slice(start, i)));\n start = i + 1;\n }\n }\n conditions.push(deserializeLogicalCondition(innerStr.slice(start)));\n\n return { type, conditions };\n }\n\n // FilterCondition: \"column.op.value\"\n const firstDot = str.indexOf(\".\");\n if (firstDot === -1) {\n return { column: str, operator: \"==\", value: true };\n }\n\n const column = str.substring(0, firstDot);\n const rest = str.substring(firstDot + 1);\n\n const secondDot = rest.indexOf(\".\");\n if (secondDot === -1) {\n // \"column.value\" — treat as equality (value kept as string)\n return { column, operator: \"==\", value: rest };\n }\n\n const opStr = rest.substring(0, secondDot);\n const valueStr = rest.substring(secondDot + 1);\n const operator = toCanonicalOp(opStr) ?? \"==\";\n\n // Parse list values with escape-aware splitting\n if (valueStr.startsWith(\"(\") && valueStr.endsWith(\")\")) {\n const items = splitListItems(valueStr.slice(1, -1));\n return { column, operator, value: items };\n }\n\n return { column, operator, value: valueStr };\n}\n","import {\n CollectionAccessor,\n DataDriver,\n Entity,\n EntityValues,\n FindParams,\n FindResponse,\n FindResult,\n LogicalCondition,\n RebaseData,\n RebaseSdkData,\n SDKCollectionClient,\n SDKQueryBuilderInterface,\n WhereFilterOp,\n WhereValue\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { QueryBuilder } from \"./query_builder\";\nimport { deserializeFilter } from \"./filter-dialect\";\nimport { buildCompositeId, resolvePrimaryKeys, PrimaryKeyInfo } from \"../util/identity\";\n\nexport interface EntityDataOptions {\n /**\n * Look up a collection's config by slug, to derive row addresses from its\n * primary keys.\n *\n * Called lazily rather than up front: the data layer is created by `Rebase`,\n * which sits *above* the admin that owns the collections, so a resolver\n * registered on mount would otherwise arrive too late to be seen.\n */\n resolveCollection?: (slug: string) => { properties?: Record<string, unknown> } | undefined;\n}\n\nfunction createPrimaryKeyResolver(options?: EntityDataOptions) {\n const cache = new Map<string, PrimaryKeyInfo[]>();\n const warned = new Set<string>();\n\n return function primaryKeysFor(slug: string): PrimaryKeyInfo[] {\n const cached = cache.get(slug);\n if (cached) return cached;\n\n const collection = options?.resolveCollection?.(slug);\n if (!collection) {\n // The registry may not have been registered yet. Don't memoize a\n // miss, or the collection would stay address-less for this session.\n return [];\n }\n\n const keys = resolvePrimaryKeys(collection);\n if (keys.length > 0) {\n // Memoized for the session: a collection's key does not change\n // while the app runs, and this is called once per row. Editing\n // `isId` in the schema editor needs a reload to take effect here.\n cache.set(slug, keys);\n return keys;\n }\n\n if (!warned.has(slug)) {\n warned.add(slug);\n // Silence here surfaces much later as rows that cannot be opened,\n // linked, or saved, with nothing pointing back at the cause.\n console.warn(\n `[rebase] Collection '${slug}' declares no primary key, so its rows have no address: ` +\n `detail links, caching and relations will not work for it. ` +\n `Mark the key property with \\`isId\\` in its collection config — the server logs which ` +\n `column to mark at boot, if its schema knows the key.`\n );\n }\n return keys;\n };\n}\n\n/**\n * Give a flat row the Entity view-model the admin renders.\n *\n * The address is *derived here* — it is not a column, and the row it came from\n * does not contain one. Rows carry exactly what the table has, with the types\n * Postgres returned; the id is this layer's invention, and this is the only\n * place it is minted.\n *\n * `primaryKeys` empty falls back to a literal `id` on the row: drivers other\n * than postgres still serve rows with one, and this keeps them working.\n */\nfunction rowToEntity<M extends Record<string, unknown>>(\n row: Record<string, unknown>,\n slug: string,\n primaryKeys: PrimaryKeyInfo[] = []\n): Entity<M> {\n return {\n id: primaryKeys.length > 0\n ? buildCompositeId(row, primaryKeys)\n : row.id as string | number,\n path: slug,\n values: row as EntityValues<M>\n };\n}\n\nfunction createDriverAccessor<M extends Record<string, unknown> = Record<string, unknown>>(\n driver: DataDriver,\n slug: string,\n getPks: () => PrimaryKeyInfo[] = () => []\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams<M>): Promise<FindResponse<M>> {\n // Ensure filters are in canonical [op, value] format even if passed as PostgREST strings\n const filter = params?.where ? deserializeFilter(params.where as Record<string, unknown>) : undefined;\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n\n // Use the RestFetchService for include-aware queries when available\n const fetchService = driver.restFetchService;\n const rows = (fetchService && params?.include && params.include.length > 0)\n ? await fetchService.fetchCollectionForRest(\n slug,\n {\n filter,\n limit: params?.limit,\n offset: params?.offset,\n orderBy: params?.orderBy?.[0],\n order: params?.orderBy?.[1],\n searchString: params?.searchString\n },\n params.include\n )\n : await driver.fetchCollection<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter,\n orderBy: params?.orderBy?.[0],\n order: params?.orderBy?.[1],\n searchString: params?.searchString\n });\n\n // Compute real total when count is available\n let total = rows.length + offset;\n let hasMore = rows.length >= limit;\n if (driver.count) {\n total = await driver.count({ path: slug, filter });\n hasMore = offset + rows.length < total;\n }\n\n return {\n data: rows.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug, getPks())),\n meta: { total, limit, offset, hasMore }\n };\n },\n\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n const row = await driver.fetchOne<M>({ path: slug, id: id });\n return row ? rowToEntity<M>(row, slug, getPks()) : undefined;\n },\n\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n const row = await driver.save<M>({\n path: slug,\n values: data,\n id: id,\n status: \"new\"\n });\n return rowToEntity<M>(row, slug, getPks());\n },\n\n createMany: driver.saveMany\n ? async (data: Partial<EntityValues<M>>[], options?: { upsert?: boolean }): Promise<Entity<M>[]> => {\n const rows = await driver.saveMany!<M>({\n path: slug,\n rows: data,\n upsert: options?.upsert\n });\n return rows.map((row) => rowToEntity<M>(row, slug, getPks()));\n }\n : undefined,\n\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n const row = await driver.save<M>({\n path: slug,\n values: data,\n id: id,\n status: \"existing\"\n });\n return rowToEntity<M>(row, slug, getPks());\n },\n\n async delete(id: string | number): Promise<void> {\n return driver.delete({\n row: { id,\npath: slug,\nvalues: {} as Record<string, unknown> }\n });\n },\n\n count: driver.count\n ? async (params?: FindParams<M>): Promise<number> => {\n const filter = params?.where ? deserializeFilter(params.where as Record<string, unknown>) : undefined;\n return driver.count!({\n path: slug,\n filter\n });\n }\n : undefined,\n\n listen: driver.listenCollection\n ? (params: FindParams<M> | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void) => {\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n return driver.listenCollection!<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter: params?.where,\n orderBy: params?.orderBy?.[0],\n order: params?.orderBy?.[1],\n searchString: params?.searchString,\n onUpdate: (entities) => {\n onUpdate({\n data: entities.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug, getPks())),\n meta: {\n total: entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n });\n },\n onError\n });\n } : undefined,\n\n listenById: driver.listenOne\n ? (id: string | number, onUpdate: (entity: Entity<M> | undefined) => void, onError?: (error: Error) => void) => {\n return driver.listenOne!<M>({\n path: slug,\n id: id,\n onUpdate: (entity) => onUpdate(entity ? rowToEntity<M>(entity, slug, getPks()) : undefined),\n onError\n });\n } : undefined,\n\n // Fluent Query Builder\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy(column: keyof M & string, ascending?: \"asc\" | \"desc\") {\n return new QueryBuilder<M>(accessor).orderBy(column, ascending);\n },\n limit(count: number) {\n return new QueryBuilder<M>(accessor).limit(count);\n },\n offset(count: number) {\n return new QueryBuilder<M>(accessor).offset(count);\n },\n search(searchString: string) {\n return new QueryBuilder<M>(accessor).search(searchString);\n },\n include(...relations: string[]) {\n return new QueryBuilder<M>(accessor).include(...relations);\n }\n };\n\n return accessor;\n}\n\n/**\n * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.\n *\n * This is the key bridge: any property access like `data.products` returns\n * a `CollectionAccessor` backed by the underlying DataDriver, without\n * needing per-collection code generation.\n *\n * @example\n * const data = buildRebaseData(driver);\n * await data.products.create({ name: \"Camera\", price: 299 });\n * const { data: items } = await data.products.find({ where: { status: [\"==\", \"published\"] } });\n */\nexport function buildRebaseData(driver: DataDriver, options?: EntityDataOptions): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n const primaryKeysFor = createPrimaryKeyResolver(options);\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = createDriverAccessor(driver, slug, () => primaryKeysFor(slug));\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = {\n collection: getAccessor\n } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs\n const slug = toSnakeCase(prop);\n return getAccessor(slug);\n }\n });\n}\n\n// =============================================================================\n// SDK data — flat rows (symmetric with the frontend SDK client)\n// =============================================================================\n\n/**\n * Unwrap a Entity back into the flat row it was built from. `rowToEntity` keeps\n * the row untouched under `.values` and derives `.id` alongside it, so dropping\n * the wrapper is the whole operation — the address was never part of the row.\n */\nfunction entityToRow<M extends Record<string, unknown>>(entity: Entity<M>): M {\n return entity.values as unknown as M;\n}\n\n/**\n * Fluent query builder for the flat SDK data layer. Mirrors {@link QueryBuilder}\n * but resolves to `FindResult<M>` (flat rows) instead of Entity-wrapped\n * `FindResponse<M>`.\n */\nclass SdkQueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements SDKQueryBuilderInterface<M> {\n private params: FindParams = { where: {} };\n\n constructor(private client: SDKCollectionClient<M>) {}\n\n where<K extends keyof M & string>(column: K, operator: WhereFilterOp, value: WhereValue<M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown): this {\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n this.params.logical = columnOrCondition as LogicalCondition;\n return this;\n }\n if (!this.params.where) this.params.where = {};\n const column = columnOrCondition as string;\n const condition: [WhereFilterOp, unknown] = [operator!, value];\n const existing = this.params.where[column];\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [WhereFilterOp, unknown][]).push(condition);\n } else {\n let firstCondition: [WhereFilterOp, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [WhereFilterOp, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n return this;\n }\n\n orderBy(column: keyof M & string, direction: \"asc\" | \"desc\" = \"asc\"): this {\n this.params.orderBy = [column, direction];\n return this;\n }\n\n limit(count: number): this { this.params.limit = count; return this; }\n offset(count: number): this { this.params.offset = count; return this; }\n search(searchString: string): this { this.params.searchString = searchString; return this; }\n include(...relations: string[]): this { this.params.include = relations; return this; }\n\n async find(): Promise<FindResult<M>> {\n return this.client.find(this.params as FindParams<M>);\n }\n\n async count(): Promise<number> {\n return this.client.count ? this.client.count(this.params as FindParams<M>) : 0;\n }\n\n listen(onUpdate: (data: FindResult<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.client.listen) {\n throw new Error(\"Listen is only available when the driver supports realtime.\");\n }\n return this.client.listen(this.params as FindParams<M>, onUpdate, onError);\n }\n}\n\n/**\n * Wrap a Entity-shaped {@link CollectionAccessor} into a flat\n * {@link SDKCollectionClient}. Every returned record is unwrapped to a flat row\n * so the backend SDK is byte-for-byte the same shape as the frontend client.\n */\nfunction toSdkCollectionClient<M extends Record<string, unknown>>(\n snap: CollectionAccessor<M>\n): SDKCollectionClient<M> {\n const client: SDKCollectionClient<M> = {\n async find(params?: FindParams<M>): Promise<FindResult<M>> {\n const res = await snap.find(params);\n return { data: res.data.map(entityToRow), meta: res.meta };\n },\n async findById(id: string | number): Promise<M | undefined> {\n const s = await snap.findById(id);\n return s ? entityToRow(s) : undefined;\n },\n async create(data: Partial<M>, id?: string | number): Promise<M> {\n return entityToRow(await snap.create(data as Partial<EntityValues<M>>, id));\n },\n async createMany(data: Partial<M>[], options?: { upsert?: boolean }): Promise<M[]> {\n if (!Array.isArray(data)) {\n throw new TypeError(\"createMany expects an array of records.\");\n }\n if (data.length === 0) return [];\n if (!snap.createMany) {\n throw new Error(\n \"Bulk writes are not supported by this collection's data source. \" +\n \"Fall back to create() per record.\"\n );\n }\n const rows = await snap.createMany(data as Partial<EntityValues<M>>[], options);\n return rows.map(entityToRow);\n },\n async update(id: string | number, data: Partial<M>): Promise<M> {\n return entityToRow(await snap.update(id, data as Partial<EntityValues<M>>));\n },\n delete(id: string | number): Promise<void> {\n return snap.delete(id);\n },\n count: snap.count ? (params?: FindParams<M>) => snap.count!(params) : undefined,\n listen: snap.listen\n ? (params: FindParams<M> | undefined, onUpdate: (r: FindResult<M>) => void, onError?: (e: Error) => void) =>\n snap.listen!(params, (res) => onUpdate({ data: res.data.map(entityToRow), meta: res.meta }), onError)\n : undefined,\n listenById: snap.listenById\n ? (id: string | number, onUpdate: (r: M | undefined) => void, onError?: (e: Error) => void) =>\n snap.listenById!(id, (s) => onUpdate(s ? entityToRow(s) : undefined), onError)\n : undefined,\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new SdkQueryBuilder<M>(client);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy: (column: keyof M & string, direction?: \"asc\" | \"desc\") => new SdkQueryBuilder<M>(client).orderBy(column, direction),\n limit: (count: number) => new SdkQueryBuilder<M>(client).limit(count),\n offset: (count: number) => new SdkQueryBuilder<M>(client).offset(count),\n search: (searchString: string) => new SdkQueryBuilder<M>(client).search(searchString),\n include: (...relations: string[]) => new SdkQueryBuilder<M>(client).include(...relations)\n };\n return client;\n}\n\n/**\n * Wrap a flat {@link SDKCollectionClient} into a Entity-shaped\n * {@link CollectionAccessor}. Every returned row is re-wrapped into the\n * `{ id, path, values }` view-model the admin CMS renders.\n */\nfunction toEntityAccessor<M extends Record<string, unknown>>(\n sdk: SDKCollectionClient<M>,\n slug: string,\n getPks: () => PrimaryKeyInfo[] = () => []\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams<M>): Promise<FindResponse<M>> {\n const res = await sdk.find(params);\n return { data: res.data.map((row) => rowToEntity<M>(row, slug, getPks())), meta: res.meta };\n },\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n const row = await sdk.findById(id);\n return row ? rowToEntity<M>(row, slug, getPks()) : undefined;\n },\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n return rowToEntity<M>(await sdk.create(data as Partial<M>, id), slug, getPks());\n },\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n const row = await sdk.update(id, data as Partial<M>);\n if (!row) throw new Error(`Update returned no data for id ${id}`);\n return rowToEntity<M>(row, slug, getPks());\n },\n delete(id: string | number): Promise<void> {\n return sdk.delete(id);\n },\n count: sdk.count ? (params?: FindParams<M>) => sdk.count!(params) : undefined,\n listen: sdk.listen\n ? (params: FindParams<M> | undefined, onUpdate: (r: FindResponse<M>) => void, onError?: (e: Error) => void) =>\n sdk.listen!(params, (res) => onUpdate({ data: res.data.map((row) => rowToEntity<M>(row, slug, getPks())), meta: res.meta }), onError)\n : undefined,\n listenById: sdk.listenById\n ? (id: string | number, onUpdate: (s: Entity<M> | undefined) => void, onError?: (e: Error) => void) =>\n sdk.listenById!(id, (row) => onUpdate(row ? rowToEntity<M>(row, slug, getPks()) : undefined), onError)\n : undefined,\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy: (column: keyof M & string, direction?: \"asc\" | \"desc\") => new QueryBuilder<M>(accessor).orderBy(column, direction),\n limit: (count: number) => new QueryBuilder<M>(accessor).limit(count),\n offset: (count: number) => new QueryBuilder<M>(accessor).offset(count),\n search: (searchString: string) => new QueryBuilder<M>(accessor).search(searchString),\n include: (...relations: string[]) => new QueryBuilder<M>(accessor).include(...relations)\n };\n return accessor;\n}\n\n/**\n * Wrap a flat {@link RebaseSdkData} into a Entity-shaped {@link RebaseData}.\n *\n * This is the **CMS boundary**: the SDK client (`client.data`) returns flat\n * rows, but the admin renders the `Entity` view-model (`entity.values.*`).\n * `core/Rebase.tsx` wraps `client.data` through this before handing it to the\n * CMS `RebaseDataContext` — without it the admin renders rows with only their\n * `id`.\n */\nexport function wrapAsEntityData(sdkData: RebaseSdkData, options?: EntityDataOptions): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n const primaryKeysFor = createPrimaryKeyResolver(options);\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = toEntityAccessor(sdkData.collection(slug), slug, () => primaryKeysFor(slug));\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = { collection: getAccessor } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n if (typeof prop === \"symbol\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n return getAccessor(toSnakeCase(prop));\n }\n });\n}\n\n/**\n * Wrap a Entity-shaped {@link RebaseData} into a flat {@link RebaseSdkData}.\n *\n * Every collection accessor is adapted to return flat rows. Use this to derive\n * the flat SDK data layer (`context.data`) from an existing Entity data layer\n * — e.g. the admin routes its Entity data via `useData()` and exposes the\n * same routing as flat `context.data` for callbacks by wrapping it here.\n */\nexport function wrapAsSdkData(entityData: RebaseData): RebaseSdkData {\n const cache = new Map<string, SDKCollectionClient>();\n\n function getAccessor(slug: string): SDKCollectionClient {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = toSdkCollectionClient(entityData.collection(slug));\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = { collection: getAccessor } as RebaseSdkData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n if (typeof prop === \"symbol\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n return getAccessor(toSnakeCase(prop));\n }\n });\n}\n\n/**\n * Build a flat {@link RebaseSdkData} from a `DataDriver`.\n *\n * This is the developer-facing SDK data layer used by backend framework\n * callbacks & scripts (`context.data` / `rebase.data`). It returns flat rows —\n * identical in shape to the frontend SDK client — so the API is symmetric\n * across front and back. The admin CMS uses {@link buildRebaseData} (Entity).\n */\nexport function buildSdkData(driver: DataDriver): RebaseSdkData {\n return wrapAsSdkData(buildRebaseData(driver));\n}\n","/**\n * Table Classification\n *\n * Shared constants and pure functions for classifying database tables.\n * Used by both the server-side PostgresBackendDriver and the Studio RLS editor.\n */\n\n/** Possible categories a database table can belong to. */\nexport type TableCategory = \"rebase-internal\" | \"junction\" | \"user\";\n\n/** Schemas that are always considered Rebase-internal. */\nexport const REBASE_INTERNAL_SCHEMAS: readonly string[] = [\"rebase\", \"auth\"];\n\n/** Table-name prefixes that mark a table as Rebase-internal regardless of schema. */\nexport const REBASE_INTERNAL_PREFIXES: readonly string[] = [\n \"_rebase_\",\n \"_auth_\",\n \"drizzle_\",\n];\n\n/**\n * Synchronously classify a table based on naming conventions.\n *\n * @param tableName - The unqualified name of the table.\n * @param schemaName - The schema the table belongs to (e.g. `\"public\"`, `\"rebase\"`).\n * @returns `\"rebase-internal\"` when the table belongs to a reserved schema or\n * carries a reserved prefix; `\"user\"` otherwise.\n *\n * @remarks\n * Junction-table detection requires an async database query and is therefore\n * **not** handled by this function. Use {@link detectJunctionTables} to obtain\n * the set of junction tables, then reclassify as needed.\n */\nexport function classifyTable(\n tableName: string,\n schemaName: string,\n): TableCategory {\n if (\n REBASE_INTERNAL_SCHEMAS.includes(schemaName) ||\n REBASE_INTERNAL_PREFIXES.some((prefix) => tableName.startsWith(prefix))\n ) {\n return \"rebase-internal\";\n }\n\n return \"user\";\n}\n\n/**\n * Convenience predicate that checks whether a table is Rebase-internal.\n *\n * @param tableName - The unqualified name of the table.\n * @param schemaName - The schema the table belongs to.\n * @returns `true` if the table is classified as `\"rebase-internal\"`.\n */\nexport function isRebaseInternalTable(\n tableName: string,\n schemaName: string,\n): boolean {\n return classifyTable(tableName, schemaName) === \"rebase-internal\";\n}\n\n/** SQL query that detects junction tables in the `public` schema. */\nexport const JUNCTION_TABLES_SQL = `\n SELECT t.table_name\n FROM information_schema.tables t\n WHERE t.table_schema = 'public'\n AND t.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.columns c\n WHERE c.table_schema = t.table_schema\n AND c.table_name = t.table_name\n AND c.column_name NOT IN (\n SELECT kcu.column_name\n FROM information_schema.key_column_usage kcu\n JOIN information_schema.table_constraints tc\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n WHERE tc.constraint_type = 'FOREIGN KEY'\n AND kcu.table_schema = t.table_schema\n AND kcu.table_name = t.table_name\n )\n )\n`;\n\n/**\n * Asynchronously detect junction (link) tables in the `public` schema.\n *\n * A junction table is defined as a table where **every** column participates in\n * at least one foreign-key constraint.\n *\n * @param executeSql - A callback that executes a raw SQL string and returns the\n * resulting rows.\n * @returns A `Set` containing the names of all detected junction tables.\n */\nexport async function detectJunctionTables(\n executeSql: (sql: string) => Promise<Record<string, unknown>[]>,\n): Promise<Set<string>> {\n const rows = await executeSql(JUNCTION_TABLES_SQL);\n const junctionTables = new Set<string>();\n\n for (const row of rows) {\n if (typeof row.table_name === \"string\") {\n junctionTables.add(row.table_name);\n }\n }\n\n return junctionTables;\n}\n"],"x_google_ignoreList":[2,20,22],"mappings":";;;;;;AAAA,IAAa,sBAAsB;AACnC,IAAa,uBAAuB;ACUpC,IAAM,iBAAiB;AAEvB,IAAa,eAAe,QAAiB;CACzC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,MAAM,mBAAmB,IAAI,MAAM,cAAc;CACjD,IAAI,CAAC,kBAAkB,OAAO;CAC9B,OAAO,iBACF,KAAI,MAAK,EAAE,YAAY,CAAC,EACxB,KAAK,GAAG;AACjB;AAEA,SAAgB,UAAU,KAAqB;CAC3C,IAAI,CAAC,KAAK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