@rebasepro/types 0.29.0 → 0.29.2

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/index.es.js CHANGED
@@ -286,6 +286,19 @@ function isRelationAggregateSort(key) {
286
286
  function sortKeyToString(key) {
287
287
  return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;
288
288
  }
289
+ /**
290
+ * Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or
291
+ * `undefined` for any other key.
292
+ *
293
+ * @group Models
294
+ */
295
+ function parseCaseFoldedFieldPath(key) {
296
+ const match = /^(lower|upper)\(\s*([^()\s]+)\s*\)$/.exec(key);
297
+ return match ? {
298
+ fn: match[1],
299
+ field: match[2]
300
+ } : void 0;
301
+ }
289
302
  /** Maps canonical operators to their REST short-code equivalents. */
290
303
  var CANONICAL_TO_REST = {
291
304
  "==": "eq",
@@ -1087,9 +1100,58 @@ var REBASE_SCHEMA = "rebase";
1087
1100
  * the trusted server plane and `IS NOT NULL` a tautology.
1088
1101
  */
1089
1102
  var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
1103
+ /**
1104
+ * Is the caller one of this database's request roles? What a permissive
1105
+ * policy is ANDed with under `rls.policyTarget: "requestRole"`, so another
1106
+ * application's role holding a grant on the table gets nothing from it.
1107
+ * `current_user` is passed in — inside the function, which reads the recorded
1108
+ * roles with its owner's rights, `current_user` would be the owner — and the
1109
+ * sub-select makes it one evaluation per statement, not one per row.
1110
+ */
1111
+ var RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;
1090
1112
  /** The request's roles as a comma-separated string, for `string_to_array`. */
1091
1113
  var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
1092
1114
  /**
1115
+ * The Postgres role that policies granting only the server context or admins
1116
+ * are written `TO`: the injected `<table>_default_admin_*` baseline, and any
1117
+ * permissive rule whose every clause requires one of the two (`roles: ["admin"]`).
1118
+ *
1119
+ * Postgres ORs the permissive policies that apply to the current role. Written
1120
+ * `TO public`, the baseline applied to every signed-in user too, as
1121
+ * `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement
1122
+ * constant arm cannot use the owner index, so a user's owner-scoped list or
1123
+ * count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`
1124
+ * this role, the policy is not in a user's plan at all.
1125
+ *
1126
+ * It holds no privilege and cannot log in: being in it only decides which
1127
+ * policies apply, and those still test `rebase.uid() IS NULL` or the `admin`
1128
+ * role. Admin requests switch to a request role that inherits it
1129
+ * ({@link adminRequestRoleFor}); a connection that is itself subject to RLS
1130
+ * inherits it for the server context. One fixed name, so the policy text is the
1131
+ * same in every deployment and every generated migration. FROZEN.
1132
+ */
1133
+ var REBASE_ADMIN_ROLE = "rebase_admin";
1134
+ /**
1135
+ * The role an admin request runs as, for a signed-in request role: it inherits
1136
+ * that role (its grants and every policy written for it) and
1137
+ * {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared
1138
+ * `rebase_admin` itself, because roles belong to the cluster: a project with a
1139
+ * request role of its own (`rls.requestRole`) would otherwise share its admin
1140
+ * access with every other project on the cluster. FROZEN derivation.
1141
+ */
1142
+ function adminRequestRoleFor(requestRole) {
1143
+ return `${requestRole}_admin`;
1144
+ }
1145
+ /**
1146
+ * Whether a request with these roles passes `rolesOverlap(["admin"])` — the
1147
+ * test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the
1148
+ * comma-joined `app.user_roles`, so a role name with a comma in it is split
1149
+ * exactly as Postgres splits it.
1150
+ */
1151
+ function holdsAdminRole(roles) {
1152
+ return roles.join(",").split(",").includes("admin");
1153
+ }
1154
+ /**
1093
1155
  * Whether the caller is a GUEST — signed in through anonymous sign-in rather
1094
1156
  * than with an account.
1095
1157
  *
@@ -1910,17 +1972,25 @@ registerResourceKind({
1910
1972
  ],
1911
1973
  implicitDefault: true
1912
1974
  });
1913
- amendResourceKind("database", { envBases: [
1914
- "DATABASE_URL",
1915
- "DATABASE_READ_URL",
1916
- "DATABASE_DIRECT_URL",
1917
- "DATABASE_POOLED",
1918
- "ADMIN_CONNECTION_STRING",
1919
- "REBASE_DRIVER",
1920
- "DB_POOL_MAX",
1921
- "DB_POOL_IDLE_TIMEOUT",
1922
- "DB_POOL_CONNECT_TIMEOUT"
1923
- ] });
1975
+ amendResourceKind("database", {
1976
+ optionKeys: [
1977
+ "databaseId",
1978
+ "migrations",
1979
+ "extensions",
1980
+ "rls"
1981
+ ],
1982
+ envBases: [
1983
+ "DATABASE_URL",
1984
+ "DATABASE_READ_URL",
1985
+ "DATABASE_DIRECT_URL",
1986
+ "DATABASE_POOLED",
1987
+ "ADMIN_CONNECTION_STRING",
1988
+ "REBASE_DRIVER",
1989
+ "DB_POOL_MAX",
1990
+ "DB_POOL_IDLE_TIMEOUT",
1991
+ "DB_POOL_CONNECT_TIMEOUT"
1992
+ ]
1993
+ });
1924
1994
  function database(keyOrOptions = DEFAULT_RESOURCE_KEY, options = {}) {
1925
1995
  return typeof keyOrOptions === "string" ? declareResource("database", keyOrOptions, options) : declareResource("database", DEFAULT_RESOURCE_KEY, keyOrOptions);
1926
1996
  }
@@ -1945,6 +2015,33 @@ function declaredDatabaseExtensions() {
1945
2015
  }
1946
2016
  return [...names].sort();
1947
2017
  }
2018
+ /** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */
2019
+ function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
2020
+ const rls = declaredResources("database").find((d) => d.key === key)?.options.rls;
2021
+ return rls && typeof rls === "object" ? rls : {};
2022
+ }
2023
+ /**
2024
+ * The policy settings every compile path must agree on — the boot's policy
2025
+ * ensure, `rebase db generate`, the drift check — read from the one place all
2026
+ * of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /
2027
+ * `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults
2028
+ * are what Rebase compiled before these existed, except `adminPolicies`, whose
2029
+ * default (`"adminRole"`) changed what the server-or-admin policies are `TO`.
2030
+ *
2031
+ * Browser-safe: where there is no `process`, only the declaration counts.
2032
+ */
2033
+ function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
2034
+ const declared = declaredDatabaseRls(dataSource);
2035
+ const env = typeof process !== "undefined" ? process.env : void 0;
2036
+ const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();
2037
+ const envAdmin = env?.REBASE_RLS_ADMIN_POLICIES?.trim();
2038
+ const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();
2039
+ return {
2040
+ policyTarget: envTarget === "requestRole" || envTarget === "public" ? envTarget : declared.policyTarget === "requestRole" ? "requestRole" : "public",
2041
+ adminPolicies: envAdmin === "adminRole" || envAdmin === "public" ? envAdmin : declared.adminPolicies === "public" ? "public" : "adminRole",
2042
+ defaultPolicies: envDefaults === "false" ? false : envDefaults === "true" ? true : declared.defaultPolicies !== false
2043
+ };
2044
+ }
1948
2045
  registerResourceKind({
1949
2046
  kind: "bucket",
1950
2047
  engines: [
@@ -3978,7 +4075,11 @@ function aggregateAlias(fn, field, p) {
3978
4075
  function isPercentileFraction(p) {
3979
4076
  return typeof p === "number" && Number.isFinite(p) && p >= 0 && p <= 1 && Math.abs(Math.round(p * 1e3) - p * 1e3) < 1e-9;
3980
4077
  }
3981
- /** An `AggregateSelect` as a driver is handed it. */
4078
+ /**
4079
+ * An `AggregateSelect` as a driver is handed it — but for its `where`, which
4080
+ * the caller decodes into the driver's `filter` (this package has no filter
4081
+ * codec).
4082
+ */
3982
4083
  function toDriverAggregate(select) {
3983
4084
  const field = "field" in select ? select.field : void 0;
3984
4085
  const p = select.fn === "percentile" ? select.p : void 0;
@@ -3986,9 +4087,19 @@ function toDriverAggregate(select) {
3986
4087
  fn: select.fn,
3987
4088
  ...field !== void 0 ? { field } : {},
3988
4089
  ...p !== void 0 ? { p } : {},
3989
- alias: aggregateAlias(select.fn, field, p)
4090
+ alias: select.as ?? aggregateAlias(select.fn, field, p)
3990
4091
  };
3991
4092
  }
4093
+ /** Whether `timeZone` names a time zone this runtime knows: an IANA name such as `Europe/Madrid`, or `UTC`. */
4094
+ function isTimeZoneName(timeZone) {
4095
+ if (typeof timeZone !== "string" || !/^[A-Za-z][A-Za-z0-9_+\-/]*$/.test(timeZone)) return false;
4096
+ try {
4097
+ new Intl.DateTimeFormat("en-US", { timeZone });
4098
+ return true;
4099
+ } catch {
4100
+ return false;
4101
+ }
4102
+ }
3992
4103
  /** The key a group comes back under: the column's name, or `<transform>_<field>`. */
3993
4104
  function aggregateGroupKey(group) {
3994
4105
  return typeof group === "string" ? group : `${group.transform}_${group.field}`;
@@ -3998,10 +4109,11 @@ function toDriverAggregateGroup(group) {
3998
4109
  return typeof group === "string" ? group : {
3999
4110
  field: group.field,
4000
4111
  transform: group.transform,
4112
+ ...group.timeZone ? { timeZone: group.timeZone } : {},
4001
4113
  key: aggregateGroupKey(group)
4002
4114
  };
4003
4115
  }
4004
4116
  //#endregion
4005
- export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, aggregateAlias, aggregateGroupKey, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredQueueConsumers, declaredResources, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPercentileFraction, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, toDriverAggregate, toDriverAggregateGroup, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
4117
+ export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, holdsAdminRole, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPercentileFraction, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isTimeZoneName, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseCaseFoldedFieldPath, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, toDriverAggregate, toDriverAggregateGroup, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
4006
4118
 
4007
4119
  //# sourceMappingURL=index.es.js.map