@rebasepro/server 0.31.0 → 0.32.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.
Files changed (117) hide show
  1. package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
  2. package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
  3. package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
  4. package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
  5. package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
  6. package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
  7. package/dist/api/errors.d.ts +4 -0
  8. package/dist/api/rest/api-generator.d.ts +8 -0
  9. package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
  10. package/dist/auth-Bfwjg4Bg.js.map +1 -0
  11. package/dist/backend/create-backend.d.ts +6 -0
  12. package/dist/backend/options.d.ts +10 -0
  13. package/dist/backend/services.d.ts +9 -0
  14. package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
  15. package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
  16. package/dist/boot/bundle.d.ts +11 -1
  17. package/dist/boot/env.d.ts +5 -0
  18. package/dist/boot/security-headers.d.ts +15 -5
  19. package/dist/boot/static-routing.d.ts +58 -0
  20. package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
  21. package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
  22. package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
  23. package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
  24. package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
  25. package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
  26. package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
  27. package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
  28. package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
  29. package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
  30. package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
  31. package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
  32. package/dist/dist-C1vNURUy.js +19354 -0
  33. package/dist/dist-C1vNURUy.js.map +1 -0
  34. package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
  35. package/dist/errors-NVbAQU25.js.map +1 -0
  36. package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
  37. package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
  38. package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
  39. package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
  40. package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
  41. package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
  42. package/dist/functions/index.d.ts +2 -0
  43. package/dist/functions/index.js +162 -1
  44. package/dist/functions/index.js.map +1 -1
  45. package/dist/functions/rate-limit.d.ts +71 -0
  46. package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
  47. package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
  48. package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
  49. package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
  50. package/dist/index.d.ts +6 -0
  51. package/dist/index.es.js +1241 -213
  52. package/dist/index.es.js.map +1 -1
  53. package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
  54. package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
  55. package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
  56. package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
  57. package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
  58. package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
  59. package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
  60. package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
  61. package/dist/{load-schema-Cv5XLVjW.js → load-schema-B4Nv1mwq.js} +32 -4
  62. package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-B4Nv1mwq.js.map} +1 -1
  63. package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
  64. package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
  65. package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
  66. package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
  67. package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
  68. package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
  69. package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
  70. package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
  71. package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
  72. package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
  73. package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
  74. package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
  75. package/dist/push/push-options.d.ts +26 -0
  76. package/dist/push/push-routes.d.ts +30 -0
  77. package/dist/push/push-service.d.ts +13 -0
  78. package/dist/push/push-store.d.ts +45 -0
  79. package/dist/push/set-up.d.ts +25 -0
  80. package/dist/push/subscription-input.d.ts +26 -0
  81. package/dist/push/vapid-config.d.ts +35 -0
  82. package/dist/push/web-push-crypto.d.ts +44 -0
  83. package/dist/push/web-push-sender.d.ts +10 -0
  84. package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
  85. package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
  86. package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
  87. package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
  88. package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
  89. package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
  90. package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-DEGwyQmx.js} +5 -5
  91. package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
  92. package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
  93. package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
  94. package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
  95. package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
  96. package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
  97. package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
  98. package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
  99. package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
  100. package/dist/serve-spa.d.ts +12 -0
  101. package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
  102. package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
  103. package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
  104. package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
  105. package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
  106. package/dist/src-CNZB3fuE.js.map +1 -0
  107. package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-D_zNDhEU.js} +3 -3
  108. package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
  109. package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
  110. package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
  111. package/package.json +5 -5
  112. package/dist/auth-BOz84vIr.js.map +0 -1
  113. package/dist/dist-fBcYxf4h.js +0 -19354
  114. package/dist/dist-fBcYxf4h.js.map +0 -1
  115. package/dist/errors-DpTMfX77.js.map +0 -1
  116. package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
  117. package/dist/src-DLIb1O9l.js.map +0 -1
package/dist/index.es.js CHANGED
@@ -2,46 +2,46 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { $ as isValidAppHost, $t as isSchemaEditingAdmin, An as RebaseClientError, At as simulationHeaders, Bt as DEFAULT_STORAGE_SOURCE_KEY, C as isTextColumnType, Ct as AUTH_FLOW_HEADER, Dn as sortKeyToString, F as isPublicStorageKey, Fn as __require, Ft as declaredSubscriptions, G as isUiTablePreferences, Gt as resourceKeyOf, H as FIELD_OPERATORS, Ht as DEFAULT_RESOURCE_KEY, I as isPublicStoragePath, It as resourceToDataSource, J as MCP_APP_MODULES, Jt as DEFAULT_DATA_SOURCE_KEY, K as mergeUiTablePreferences, Kt as resourceKind, L as storageObjectPath, Lt as resourceToStorageSource, M as toDriverAggregateGroup, Mn as unsupportedMethod, N as storageTargetsInText, Nn as __commonJSMin, Nt as declaredQueueConsumers, P as PUBLIC_STORAGE_PREFIX, Q as SCHEMA_VERSION_HEADER, Qt as isSQLAdmin, Rt as setQueueRuntime, S as isTemporalColumnType, Ut as buildResourceGraph, V as BATCH_REF_KEY, Vt as storageEnvSuffix, W as isFieldOperation, Wt as resourceEnvSuffix, X as isContentHashedFileName, Y as computeSchemaVersion, Yt as getDataSourceCapabilities, Z as LEGACY_LAYOUT_REMEDY, _ as sql, _n as INCLUDE_COUNT_KEY, a as defineAuthTable, c as isAuthTableDef, cn as RLS_ROLES_SQL, ct as intersectScopes, et as reservedPrefixFor, f as rel, g as pgEnum, gn as policy, gt as scopeGrantsAny, h as isColumnBuilder, ht as scopeGrants, i as parseTablePatches, j as toDriverAggregate, jn as isUnsupported, jt as parseEnvBoolean, kn as RebaseApiError, l as isTableDef, ln as RLS_UID_SQL, m as col, n as TablePatchError, o as defineTable, pn as isAnonymousUid, pt as parseScope, q as uiTablePreferencesProblems, qt as resourceKinds, s as defineView, sn as RLS_JWT_SQL, st as hasAdminRole, u as isViewDef, vn as JUNCTION_PIVOT_KEY, x as isNumericColumnType, xt as summarizeScopes, y as json, yn as ALL_WHERE_FILTER_OPS, yt as scopesForRoles, z as MAX_LIST_LIMIT, zt as setTopicRuntime } from "./src-DLIb1O9l.js";
5
+ import { $ as compareStaticRoutes, $t as getDataSourceCapabilities, Bt as resourceToDataSource, C as isTextColumnType, Cn as ALL_WHERE_FILTER_OPS, Ct as scopesForRoles, Dt as AUTH_FLOW_HEADER, F as isPublicStorageKey, Fn as isUnsupported, Ft as parseEnvBoolean, G as isUiTablePreferences, Gt as storageEnvSuffix, H as FIELD_OPERATORS, Ht as setQueueRuntime, I as isPublicStoragePath, In as unsupportedMethod, J as MCP_APP_MODULES, Jt as resourceEnvSuffix, K as mergeUiTablePreferences, Kt as DEFAULT_RESOURCE_KEY, L as storageObjectPath, Ln as __commonJSMin, Lt as declaredQueueConsumers, M as toDriverAggregateGroup, N as storageTargetsInText, Nn as RebaseApiError, P as PUBLIC_STORAGE_PREFIX, Pn as RebaseClientError, Pt as simulationHeaders, Q as SCHEMA_VERSION_HEADER, Qt as DEFAULT_DATA_SOURCE_KEY, S as isTemporalColumnType, Sn as JUNCTION_PIVOT_KEY, Tt as summarizeScopes, Ut as setTopicRuntime, V as BATCH_REF_KEY, Vt as resourceToStorageSource, W as isFieldOperation, Wt as DEFAULT_STORAGE_SOURCE_KEY, X as isContentHashedFileName, Xt as resourceKind, Y as computeSchemaVersion, Yt as resourceKeyOf, Z as LEGACY_LAYOUT_REMEDY, Zt as resourceKinds, _ as sql, _n as isAnonymousUid, _t as parseScope, a as defineAuthTable, bn as policy, bt as scopeGrantsAny, c as isAuthTableDef, dn as RLS_JWT_SQL, dt as hasAdminRole, et as isValidAppHost, f as rel, fn as RLS_ROLES_SQL, ft as intersectScopes, g as pgEnum, h as isColumnBuilder, i as parseTablePatches, it as validateStaticRoute, j as toDriverAggregate, jn as sortKeyToString, l as isTableDef, m as col, n as TablePatchError, nn as isSQLAdmin, nt as parseFrameAncestor, o as defineTable, pn as RLS_UID_SQL, q as uiTablePreferencesProblems, qt as buildResourceGraph, rn as isSchemaEditingAdmin, rt as reservedPrefixFor, s as defineView, tt as matchStaticRoute, u as isViewDef, x as isNumericColumnType, xn as INCLUDE_COUNT_KEY, y as json, yt as scopeGrants, z as MAX_LIST_LIMIT, zn as __require, zt as declaredSubscriptions } from "./src-CNZB3fuE.js";
6
6
  import { a as logger, c as setLogLevel, d as hostEnv, i as logLevelEnabled, l as setLogOutput, o as rawQueryLoggingEnabled, r as describeCauseChain, s as redactSensitiveText, t as _setLogLineHook } from "./logger-SigQ2oZJ.js";
7
- import { $ as resolveEmailLinkBase, A as createDataRateLimitCheck, B as registerDevEmailSink, C as createJwksRoutes, D as AUTH_CONFIG_LIMIT, E as isBootstrapWindowOpen, F as activeDevEmailSink, G as validatePasswordStrength, H as createEmailService, I as clearActiveDevEmailSink, J as createAdapterAuthMiddleware, K as verifyPassword, L as createDevEmailSink, M as createRateLimiter, N as setSharedRateLimitStore, O as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, P as MemoryRateLimitStore, Q as assertEmailLinkBases, R as devEmailSinkFor, S as createApiKeyStore, T as configureUserPicking, U as resolveAuthHooks, V as SMTPEmailService, W as hashPassword, X as completeUserCreation, Y as createAdapterCallerResolution, Z as generateSecurePassword, _ as oauthCodeFlowSchema, a as createBitbucketProvider, at as getPasswordResetTemplate, b as createApiKeyRoutes, c as createTwitterProvider, ct as resolveEmailBranding, d as createMicrosoftProvider, dt as html, et as getEmailChangeNoticeTemplate, f as tryVerifyOidcIdToken, ft as raw, g as createGoogleProvider, gt as walkJsonShape, h as createLinkedinProvider, ht as formatJsonPath, i as createSlackProvider, it as getMagicLinkTemplate, j as createDataRateLimiter, k as createAuthLimiters, l as createFacebookProvider, lt as RawHtml, m as createGitHubProvider, mt as resolveRateLimitStoreKind, n as createCustomAuthAdapter, nt as getEmailOtpTemplate, o as createGitLabProvider, ot as getUserInvitationTemplate, p as verifyOidcIdToken, pt as createSqlRateLimitStore, q as adapterRefusal, r as createSpotifyProvider, rt as getEmailVerificationTemplate, s as createDiscordProvider, st as getWelcomeEmailTemplate, tt as getEmailChangeTemplate, u as createAppleProvider, ut as escapeHtml, v as pkceTokenParams, w as createBuiltinAuthAdapter, x as createPersonalKeyRoutes, y as providerVerifiedEmail, z as extractLinks } from "./auth-BOz84vIr.js";
7
+ import { $ as assertEmailLinkBases, A as createDataRateLimitCheck, B as extractLinks, C as createJwksRoutes, D as AUTH_CONFIG_LIMIT, E as isBootstrapWindowOpen, F as MemoryRateLimitStore, G as hashPassword, H as SMTPEmailService, I as activeDevEmailSink, J as adapterRefusal, K as validatePasswordStrength, L as clearActiveDevEmailSink, M as createRateLimiter, N as requestClientAddress, O as DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT, P as setSharedRateLimitStore, Q as generateSecurePassword, R as createDevEmailSink, S as createApiKeyStore, T as configureUserPicking, U as createEmailService, V as registerDevEmailSink, W as resolveAuthHooks, X as createAdapterCallerResolution, Y as createAdapterAuthMiddleware, Z as completeUserCreation, _ as oauthCodeFlowSchema, _t as walkJsonShape, a as createBitbucketProvider, at as getMagicLinkTemplate, b as createApiKeyRoutes, c as createTwitterProvider, ct as getWelcomeEmailTemplate, d as createMicrosoftProvider, dt as escapeHtml, et as resolveEmailLinkBase, f as tryVerifyOidcIdToken, ft as html, g as createGoogleProvider, gt as formatJsonPath, h as createLinkedinProvider, ht as resolveRateLimitStoreKind, i as createSlackProvider, it as getEmailVerificationTemplate, j as createDataRateLimiter, k as createAuthLimiters, l as createFacebookProvider, lt as resolveEmailBranding, m as createGitHubProvider, mt as createSqlRateLimitStore, n as createCustomAuthAdapter, nt as getEmailChangeTemplate, o as createGitLabProvider, ot as getPasswordResetTemplate, p as verifyOidcIdToken, pt as raw, q as verifyPassword, r as createSpotifyProvider, rt as getEmailOtpTemplate, s as createDiscordProvider, st as getUserInvitationTemplate, tt as getEmailChangeNoticeTemplate, u as createAppleProvider, ut as RawHtml, v as pkceTokenParams, w as createBuiltinAuthAdapter, x as createPersonalKeyRoutes, y as providerVerifiedEmail, z as devEmailSinkFor } from "./auth-Bfwjg4Bg.js";
8
8
  import { r as toSnakeCase } from "./strings.es-k0kjzQBh.js";
9
- import { a as serializeTables, c as policyTableFromDescriptor, i as schemaViewKey, o as servedTableSlugs, r as schemaViewFor, s as tableEffectiveRules } from "./schema-tables-lJHnyqj4.js";
10
- import { a as textMaxLength, i as firstDuplicate, n as buildTableSchema, o as validationPattern, s as isSoftDeleteRestore, t as buildTableInputSchema } from "./openapi-generator-CoAFACMx.js";
11
- import { c as createTransport, f as withETag, l as defaultCodeForStatus, p as unref, r as SDKQueryBuilder, s as createTableClient, u as invalidBulkBody } from "./offline-store-DtmBwmKE-B17N4609.js";
9
+ import { a as serializeTables, c as policyTableFromDescriptor, i as schemaViewKey, o as servedTableSlugs, r as schemaViewFor, s as tableEffectiveRules } from "./schema-tables-DKFg6vMV.js";
10
+ import { a as textMaxLength, i as firstDuplicate, n as buildTableSchema, o as validationPattern, s as isSoftDeleteRestore, t as buildTableInputSchema } from "./openapi-generator-CAhJiwBm.js";
11
+ import { c as createTransport, f as withETag, l as defaultCodeForStatus, p as unref, r as SDKQueryBuilder, s as createTableClient, u as invalidBulkBody } from "./offline-store-DtmBwmKE-C9ba2NJv.js";
12
12
  import "./resumable-upload-threshold-CKv-Ry0l.js";
13
- import { i as revokeInternalTableSql, t as REBASE_INTERNAL_TABLES } from "./internal-tables-CHFJHH7N.js";
13
+ import { a as revokeInternalTableSql, n as REBASE_INTERNAL_TABLES, t as LOAD_REQUEST_ROLES_PLPGSQL } from "./internal-tables-XxM_NdR_.js";
14
14
  import { a as warnDeprecated, n as FilesFailedToLoadError } from "./dynamic-import-Bi3XK5y-.js";
15
15
  import { i as canReadColumn, n as apiHiddenKeys, o as canWriteColumn, s as canWriteRelation, u as restrictedKeys } from "./access-D1CTJSLK.js";
16
- import { a as loadBackendSchema, d as isSchemaDefinitionError, i as isSchemaLoadError, n as compileLoadedSchema, r as compileSchemaDefs, t as SchemaLoadError } from "./load-schema-Cv5XLVjW.js";
17
- import { a as parseWriteFilter, c as assertQueryFieldsReadable, d as relationOf, f as relationsOfKind, h as reconcileCursorOrder, i as parseQueryOptions, l as assertReadableFields, m as decodeCursor$1, n as parseAggregateSelect, o as resolveListLimitParam, p as cursorToStartAfter, r as parseGroupBy, s as assertNoHiddenAggregateNames, t as orderByEntriesToTuples, u as requestViewer } from "./query-parser-D9Uf8aha.js";
18
- import { _ as normalizeOrderBy, c as collectAllPages, g as OrderBySpecError, l as paginateFind, m as normalizeInclude, p as mergeIncludeSpecs, r as deserializeFilter, t as RESERVED_QUERY_KEYS, u as resolveFindWindow, v as serializeOrderBy } from "./filter-dialect-DAVl1Nsm.js";
19
- import { C as randomHex, E as sha256Hex, S as constantTimeEqual, T as sha256Bytes, b as normalizePemFromEnv, d as hasAsymmetricSigningKey, g as setDefaultJwtService, h as processJwtService, l as getJwks, m as jwtOf, n as configureJwt, r as createJwtService, y as verifyJwt } from "./jwt-JtQiewBW.js";
16
+ import { a as loadBackendSchema, d as isSchemaDefinitionError, i as isSchemaLoadError, n as compileLoadedSchema, r as compileSchemaDefs, t as SchemaLoadError } from "./load-schema-B4Nv1mwq.js";
17
+ import { a as parseWriteFilter, c as assertQueryFieldsReadable, d as relationOf, f as relationsOfKind, h as reconcileCursorOrder, i as parseQueryOptions, l as assertReadableFields, m as decodeCursor$1, n as parseAggregateSelect, o as resolveListLimitParam, p as cursorToStartAfter, r as parseGroupBy, s as assertNoHiddenAggregateNames, t as orderByEntriesToTuples, u as requestViewer } from "./query-parser-Cd70kZO8.js";
18
+ import { _ as normalizeOrderBy, c as collectAllPages, g as OrderBySpecError, l as paginateFind, m as normalizeInclude, p as mergeIncludeSpecs, r as deserializeFilter, t as RESERVED_QUERY_KEYS, u as resolveFindWindow, v as serializeOrderBy } from "./filter-dialect-XtPJOCbD.js";
19
+ import { C as randomHex, E as sha256Hex, S as constantTimeEqual, T as sha256Bytes, b as normalizePemFromEnv, d as hasAsymmetricSigningKey, g as setDefaultJwtService, h as processJwtService, l as getJwks, m as jwtOf, n as configureJwt, r as createJwtService, y as verifyJwt } from "./jwt-CqhXs8Iz.js";
20
20
  import { a as isConcurrentDdlRace, c as provisioningExec, l as withoutLeadingComments, o as isDuplicateObjectRace, r as createDdlBootstrapper, s as isSchemaChange, t as CONCURRENT_DDL_SQLSTATES } from "./ddl-bootstrap-DhCuwhHM.js";
21
- import { t as createCronStore } from "./cron-store-91cd9Qzv.js";
22
- import { a as isDataException, c as dbConnectionErrorCounts, i as errorHandler, n as DATABASE_UNAVAILABLE_MESSAGE, o as isDatabaseUnreachable, r as declaredErrorAnswer, s as schemaDriftRemedy, t as ApiError } from "./errors-DpTMfX77.js";
23
- import { n as HARD_DELETE_QUERY_PARAM, r as parseHardDelete } from "./soft-delete-params-DDRmxT2z.js";
24
- import { $ as supportsRlsScoping, A as isDownloadTokenGrant, C as publicObjectAuth, D as requireAuth, E as requireAdmin, G as createTusScopeGuard, H as reportSimulatedContext, I as decideImpersonation, J as validateApiKey, K as isApiKeyToken, L as refuseUnhonouredImpersonation, M as requestedStorageObject, N as storageObjectOfPath, O as userFromToken, P as storageRequestWildcard, Q as scopeDataDriver, S as optionalAuth, T as refuse$1, U as createApiKeyPreAuth, W as createFunctionScopeGuard, X as safeCompare, Y as extractBearerToken, Z as SERVICE_IDENTITY, _ as setDefaultAccessControl, at as refuseSimulatedWrite, b as extractUserFromToken, c as configureAccess, d as keyOwnerResolverFor, f as processAccessControl, g as scopeMissing, h as requireScopeByMethod, j as isPublicObjectGrant, k as PUBLIC_OBJECT_PRINCIPAL, l as getAccessModel, m as requireScope, n as accessModelFromAuthTable, ot as httpMethodToOperation, q as resolveApiKey, r as accessOf, s as callerScopes, tt as isAccessTokenRevoked, u as hasScope, v as createAuthMiddleware, w as queryTokenAuth, x as fileTokenAuth, y as createRequireAuth } from "./access-Dtu87BMj.js";
25
- import { a as canonicalStorageId, i as canonicalStorageBucket, n as InvalidStorageBucketError, o as canonicalStorageKey, r as InvalidStorageKeyError, t as InvalidListOptionsError } from "./keys-BTPoSvUs.js";
26
- import { t as logMiddleware } from "./logs-routes-BT4af1Or.js";
27
- import { a as fileWebStream, d as IMAGE_MIME_TYPES, i as bytesView, l as DEFAULT_MAX_FILE_SIZE, n as ObjectTooLargeError, o as meteredChunks, s as readStreamFully, t as validateUploadedFile, u as DOCUMENT_MIME_TYPES } from "./upload-validation-B-psYLaN.js";
28
- import { t as S3StorageController } from "./S3StorageController-DDAq8Kt5.js";
29
- import { t as GCSStorageController } from "./GCSStorageController-sCw2c4aA.js";
30
- import { t as schemaCallerOf } from "./schema-tables-routes-Uss-ljon.js";
31
- import { i as usesVersionedMigrations, n as commitPathsFor, r as findProjectRoot } from "./project-root-qDQzmsUD.js";
32
- import { a as isHonoLike, i as loadFunctionsWithDiagnostics, n as loadFunctions, r as loadFunctionsFromDirectory } from "./function-loader-BeFbN1-A.js";
33
- import { a as getDriver, c as getSql, d as getUserProfile, f as hasRole, g as requireDriver, h as isAuthenticated, i as getApiKey, l as getUser, m as isAdmin, o as getRequestId, p as identityResolved, r as requireRole, s as getRoles, t as createFunctionRoutes, u as getUserId } from "./function-routes-CIwLXsZF.js";
34
- import "./proxy-D18_bcQI.js";
35
- import "./request-timeout-CpOgfQPK.js";
36
- import { t as FunctionSelectionError } from "./selection-hgC1szl6.js";
37
- import { a as loadCrons, i as loadCronJobsWithDiagnostics, n as declareCrons, r as loadCronJobsFromDirectory } from "./cron-loader-BDN8plQK.js";
38
- import { i as validateCronExpression, t as CronScheduler } from "./cron-scheduler-DgrsqyQQ.js";
39
- import { t as createCronRoutes } from "./cron-routes-BOu-bY7I.js";
40
- import { a as listBackupObjects, c as readBackupBytes, i as backupStorageFromEnv, n as createBackupLinkRoutes, o as parseBackupDestination, r as createBackupRoutes, s as parseBackupTimestamp } from "./backup-B-1oW6qX.js";
41
- import { a as defaultBackoff, i as createJobQueue, n as createJobStore, o as currentAmbientTransaction, r as PermanentJobError } from "./jobs-WCyKVsUf.js";
42
- import { t as METRIC_SERIES } from "./history-store-DseUt_dm.js";
43
- import { n as createContractRoutes } from "./contract-routes-o5oqNhfc.js";
44
- import { createHash, createSign, randomBytes } from "node:crypto";
21
+ import { t as createCronStore } from "./cron-store-FGaZOdMf.js";
22
+ import { a as isDataException, c as dbConnectionErrorCounts, i as errorHandler, n as DATABASE_UNAVAILABLE_MESSAGE, o as isDatabaseUnreachable, r as declaredErrorAnswer, s as schemaDriftRemedy, t as ApiError } from "./errors-NVbAQU25.js";
23
+ import { n as HARD_DELETE_QUERY_PARAM, r as parseHardDelete } from "./soft-delete-params-Dhn0qKFv.js";
24
+ import { $ as supportsRlsScoping, A as isDownloadTokenGrant, C as publicObjectAuth, D as requireAuth, E as requireAdmin, G as createTusScopeGuard, H as reportSimulatedContext, I as decideImpersonation, J as validateApiKey, K as isApiKeyToken, L as refuseUnhonouredImpersonation, M as requestedStorageObject, N as storageObjectOfPath, O as userFromToken, P as storageRequestWildcard, Q as scopeDataDriver, S as optionalAuth, T as refuse$1, U as createApiKeyPreAuth, W as createFunctionScopeGuard, X as safeCompare, Y as extractBearerToken, Z as SERVICE_IDENTITY, _ as setDefaultAccessControl, at as refuseSimulatedWrite, b as extractUserFromToken, c as configureAccess, d as keyOwnerResolverFor, f as processAccessControl, g as scopeMissing, h as requireScopeByMethod, j as isPublicObjectGrant, k as PUBLIC_OBJECT_PRINCIPAL, l as getAccessModel, m as requireScope, n as accessModelFromAuthTable, ot as httpMethodToOperation, q as resolveApiKey, r as accessOf, s as callerScopes, tt as isAccessTokenRevoked, u as hasScope, v as createAuthMiddleware, w as queryTokenAuth, x as fileTokenAuth, y as createRequireAuth } from "./access-BxkEYQh1.js";
25
+ import { a as canonicalStorageId, i as canonicalStorageBucket, n as InvalidStorageBucketError, o as canonicalStorageKey, r as InvalidStorageKeyError, t as InvalidListOptionsError } from "./keys-Btt6ZNqF.js";
26
+ import { t as logMiddleware } from "./logs-routes-C3CLYP-n.js";
27
+ import { a as fileWebStream, d as IMAGE_MIME_TYPES, i as bytesView, l as DEFAULT_MAX_FILE_SIZE, n as ObjectTooLargeError, o as meteredChunks, s as readStreamFully, t as validateUploadedFile, u as DOCUMENT_MIME_TYPES } from "./upload-validation-BnIwo78L.js";
28
+ import { t as S3StorageController } from "./S3StorageController-C9LjuMhL.js";
29
+ import { t as GCSStorageController } from "./GCSStorageController-B3p3aUX-.js";
30
+ import { t as schemaCallerOf } from "./schema-tables-routes-BfsNG4c4.js";
31
+ import { i as usesVersionedMigrations, n as commitPathsFor, r as findProjectRoot } from "./project-root-CIrVZi-r.js";
32
+ import { a as isHonoLike, i as loadFunctionsWithDiagnostics, n as loadFunctions, r as loadFunctionsFromDirectory } from "./function-loader-D3YEHF6E.js";
33
+ import { a as getDriver, c as getSql, d as getUserProfile, f as hasRole, g as requireDriver, h as isAuthenticated, i as getApiKey, l as getUser, m as isAdmin, o as getRequestId, p as identityResolved, r as requireRole, s as getRoles, t as createFunctionRoutes, u as getUserId } from "./function-routes-DNDFIa7t.js";
34
+ import "./proxy-clweqa43.js";
35
+ import "./request-timeout-cC3HT1Pf.js";
36
+ import { t as FunctionSelectionError } from "./selection-BOnbJvXD.js";
37
+ import { a as loadCrons, i as loadCronJobsWithDiagnostics, n as declareCrons, r as loadCronJobsFromDirectory } from "./cron-loader-BBP0kBIl.js";
38
+ import { i as validateCronExpression, t as CronScheduler } from "./cron-scheduler-CopTWKYB.js";
39
+ import { t as createCronRoutes } from "./cron-routes-Du03uJ7K.js";
40
+ import { a as listBackupObjects, c as readBackupBytes, i as backupStorageFromEnv, n as createBackupLinkRoutes, o as parseBackupDestination, r as createBackupRoutes, s as parseBackupTimestamp } from "./backup-g2ohsDe0.js";
41
+ import { a as defaultBackoff, i as createJobQueue, n as createJobStore, o as currentAmbientTransaction, r as PermanentJobError } from "./jobs-CFUwQTao.js";
42
+ import { t as METRIC_SERIES } from "./history-store-DzrJeEKv.js";
43
+ import { n as createContractRoutes } from "./contract-routes-CZTlAP7p.js";
44
+ import { createCipheriv, createECDH, createHash, createHmac, createPrivateKey, createSign, randomBytes, sign } from "node:crypto";
45
45
  import * as path$2 from "node:path";
46
46
  import path from "node:path";
47
47
  import fs, { createWriteStream, readFileSync, realpathSync } from "node:fs";
@@ -62,7 +62,7 @@ import { pathToFileURL } from "url";
62
62
  import { Readable } from "stream";
63
63
  import { promisify } from "util";
64
64
  import * as crypto$2 from "crypto";
65
- import { createHmac, randomUUID as randomUUID$1 } from "crypto";
65
+ import { createHmac as createHmac$1, randomUUID as randomUUID$1 } from "crypto";
66
66
  import { createMiddleware } from "hono/factory";
67
67
  import { z, z as z$1 } from "zod";
68
68
  import { routePath } from "hono/route";
@@ -2912,16 +2912,33 @@ function strictTransportSecurity(includeSubDomains) {
2912
2912
  return `max-age=${HSTS_MAX_AGE_SECONDS}${includeSubDomains ? "; includeSubDomains" : ""}`;
2913
2913
  }
2914
2914
  /**
2915
- * The Content-Security-Policy every static app is served with.
2915
+ * The Content-Security-Policy a static app is served with.
2916
2916
  *
2917
- * Conservative on purpose: it says who may frame the app (this origin only,
2918
- * like the `X-Frame-Options: SAMEORIGIN` already sent), forbids plugins, and
2919
- * pins `<base>` to this origin. It restricts no script, style, worker, font or
2917
+ * Conservative on purpose: it says who may frame the app (this origin, plus
2918
+ * the origins the app's `frameAncestors` names), forbids plugins, and pins
2919
+ * `<base>` to this origin. It restricts no script, style, worker, font or
2920
2920
  * connection source, because an app's own build decides those — the CMS admin
2921
2921
  * runs inline scripts, module workers and third-party sign-in, and a policy
2922
2922
  * that broke any of them would be one every project had to turn off.
2923
+ *
2924
+ * Every origin is held to `parseFrameAncestor` before it is written, and a
2925
+ * value that is not exactly one origin throws: it is about to become part of
2926
+ * a header, where a `;` would start a directive of the caller's choosing.
2927
+ *
2928
+ * `X-Frame-Options: SAMEORIGIN` is still sent beside it. A browser that reads
2929
+ * `frame-ancestors` ignores `X-Frame-Options`, as CSP Level 2 requires, so
2930
+ * the origins named here can frame the app.
2923
2931
  */
2924
- var STATIC_APP_CSP = "frame-ancestors 'self'; object-src 'none'; base-uri 'self'";
2932
+ function staticAppCsp(frameAncestors = []) {
2933
+ const origins = /* @__PURE__ */ new Set();
2934
+ for (const value of frameAncestors) {
2935
+ const result = parseFrameAncestor(value);
2936
+ if (!result.ok) throw new Error(`frameAncestors: ${JSON.stringify(value)} ${result.reason}.`);
2937
+ origins.add(result.origin);
2938
+ }
2939
+ return `frame-ancestors ${["'self'", ...origins].join(" ")}; object-src 'none'; base-uri 'self'`;
2940
+ }
2941
+ staticAppCsp();
2925
2942
  /**
2926
2943
  * The `Referrer-Policy` this runtime sends: `strict-origin-when-cross-origin`,
2927
2944
  * the browsers' own default. A cross-origin request carries the page's origin
@@ -3371,6 +3388,7 @@ function servedFrontendPaths() {
3371
3388
  function serveSPA(app, config) {
3372
3389
  if (!servedFrontends.includes(config.frontendPath)) servedFrontends.push(config.frontendPath);
3373
3390
  const { frontendPath, apiBasePath = "/api", excludePaths = [], indexFile = "index.html", spa = true } = config;
3391
+ const contentSecurityPolicy = staticAppCsp(config.frameAncestors);
3374
3392
  const rawBase = config.basePath ?? "/";
3375
3393
  const basePath = rawBase !== "/" ? rawBase.replace(/\/+$/, "") : "/";
3376
3394
  const isRoot = basePath === "/";
@@ -3391,7 +3409,7 @@ function serveSPA(app, config) {
3391
3409
  app.use(scope, async (c, next) => {
3392
3410
  if (declines(c)) return next();
3393
3411
  await next();
3394
- if (!isExcludedFromApp(c.req.path) && !c.res.headers.has("content-security-policy")) c.header("Content-Security-Policy", STATIC_APP_CSP);
3412
+ if (!isExcludedFromApp(c.req.path) && !c.res.headers.has("content-security-policy")) c.header("Content-Security-Policy", contentSecurityPolicy);
3395
3413
  if (c.res.headers.has("cache-control")) return;
3396
3414
  if (c.res.status !== 200 && c.res.status !== 304) return;
3397
3415
  c.header("Cache-Control", isContentHashed(c.req.path) ? IMMUTABLE_CACHE : REVALIDATE_CACHE);
@@ -5709,6 +5727,75 @@ function createFunctionsClient(transport) {
5709
5727
  return transport.request(routePath, init);
5710
5728
  } };
5711
5729
  }
5730
+ /** A VAPID key, as base64url, in the form `PushManager.subscribe` takes. */
5731
+ function keyBytes(base64url) {
5732
+ const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(base64url.length / 4) * 4, "=");
5733
+ const binary = atob(base64);
5734
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
5735
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
5736
+ return bytes;
5737
+ }
5738
+ function sameKey(current, wanted) {
5739
+ if (!current) return false;
5740
+ const bytes = new Uint8Array(current);
5741
+ return bytes.length === wanted.length && bytes.every((byte, i) => byte === wanted[i]);
5742
+ }
5743
+ function supported() {
5744
+ return typeof navigator !== "undefined" && "serviceWorker" in navigator && typeof window !== "undefined" && "PushManager" in window && "Notification" in window;
5745
+ }
5746
+ function createPushClient(transport, pushPath = "/push") {
5747
+ const registrationOf = async (options) => {
5748
+ if (!supported()) throw new RebaseClientError("This browser does not support push notifications.", { code: "PUSH_UNSUPPORTED" });
5749
+ const registration = options?.registration ?? await navigator.serviceWorker.getRegistration();
5750
+ if (!registration) throw new RebaseClientError("Push needs a service worker: register one first, e.g. navigator.serviceWorker.register(\"/sw.js\").", { code: "PUSH_NO_SERVICE_WORKER" });
5751
+ return registration;
5752
+ };
5753
+ return {
5754
+ isSupported: supported,
5755
+ async getSubscription(options) {
5756
+ if (!supported()) return null;
5757
+ const registration = options?.registration ?? await navigator.serviceWorker.getRegistration();
5758
+ return registration ? registration.pushManager.getSubscription() : null;
5759
+ },
5760
+ async subscribe(options) {
5761
+ const registration = await registrationOf(options);
5762
+ if ((Notification.permission === "default" ? await Notification.requestPermission() : Notification.permission) !== "granted") throw new RebaseClientError("Notifications are blocked for this site.", { code: "PUSH_PERMISSION_DENIED" });
5763
+ const { key } = await transport.request(`${pushPath}/key`, { method: "GET" });
5764
+ const applicationServerKey = keyBytes(key);
5765
+ let subscription = await registration.pushManager.getSubscription();
5766
+ if (subscription && !sameKey(subscription.options.applicationServerKey, applicationServerKey)) {
5767
+ await subscription.unsubscribe();
5768
+ subscription = null;
5769
+ }
5770
+ subscription ??= await registration.pushManager.subscribe({
5771
+ userVisibleOnly: true,
5772
+ applicationServerKey
5773
+ });
5774
+ const lang = options?.lang ?? (typeof navigator !== "undefined" ? navigator.language : void 0);
5775
+ const { id } = await transport.request(`${pushPath}/subscriptions`, {
5776
+ method: "POST",
5777
+ body: JSON.stringify({
5778
+ subscription: subscription.toJSON(),
5779
+ lang
5780
+ })
5781
+ });
5782
+ return {
5783
+ id,
5784
+ subscription
5785
+ };
5786
+ },
5787
+ async unsubscribe(options) {
5788
+ const subscription = await this.getSubscription(options);
5789
+ if (!subscription) return false;
5790
+ await transport.request(`${pushPath}/subscriptions`, {
5791
+ method: "DELETE",
5792
+ body: JSON.stringify({ endpoint: subscription.endpoint })
5793
+ });
5794
+ await subscription.unsubscribe();
5795
+ return true;
5796
+ }
5797
+ };
5798
+ }
5712
5799
  /**
5713
5800
  * Create a StorageSource that talks to the Rebase backend REST API.
5714
5801
  *
@@ -8647,7 +8734,7 @@ var LazyOfflineManager = class {
8647
8734
  keepsLastUser;
8648
8735
  constructor(config, createInner) {
8649
8736
  this.keepsLastUser = config.keepLastUser === true;
8650
- import("./offline-D_wKJcO3-RV6C9HnX.js").then(({ OfflineManager: Engine }) => {
8737
+ import("./offline-ET6xI1ZO-BQpLQ7wh.js").then(({ OfflineManager: Engine }) => {
8651
8738
  const engine = new Engine(config, createInner);
8652
8739
  this.engine = engine;
8653
8740
  const queued = this.queued;
@@ -8843,6 +8930,7 @@ function createRebaseClient(options) {
8843
8930
  const personalKeys = createPersonalKeys(transport, options.personalKeys);
8844
8931
  const storage = createStorage(transport);
8845
8932
  const functions = createFunctionsClient(transport);
8933
+ const push = createPushClient(transport);
8846
8934
  const createStorageSource = (storageId) => storageId === "(default)" ? storage : createStorage(transport, storageId);
8847
8935
  const storageRegistry = new ClientStorageSourceRegistry();
8848
8936
  storageRegistry.register(DEFAULT_STORAGE_SOURCE_KEY, storage);
@@ -9093,6 +9181,7 @@ function createRebaseClient(options) {
9093
9181
  apiKeys,
9094
9182
  personalKeys,
9095
9183
  functions,
9184
+ push,
9096
9185
  storage,
9097
9186
  storageRegistry,
9098
9187
  createStorageSource,
@@ -12641,12 +12730,20 @@ var RestApiGenerator = class RestApiGenerator {
12641
12730
  * anyway, on the same principle as the database diagnostics one layer up:
12642
12731
  * structured fields are for the people building against this, and a
12643
12732
  * deployed API answers strangers.
12644
- */
12645
- entityNotFound(collection, id) {
12733
+ *
12734
+ * `read` marks the 404 of a `GET` by id as expected (see
12735
+ * {@link ApiError.expected}), so the request log writes it at info. Asking
12736
+ * whether a row exists is what a read by id is for: the SDK's `findById`
12737
+ * turns this answer into `null`, and an app looking up a code a user typed
12738
+ * gets it whenever the code has expired. Logged at warn, one such lookup
12739
+ * per visitor filled a `--level warn` read of the log with misses. A write
12740
+ * that names a missing row stays at warn: it acts on an id it believed in.
12741
+ */
12742
+ entityNotFound(collection, id, read = false) {
12646
12743
  return new ApiError(404, "NOT_FOUND", `No row with id '${id}' in '${collection}'. It may not exist, or it may be hidden from this caller by row-level security.`, hostEnv().NODE_ENV === "production" ? void 0 : {
12647
12744
  collection,
12648
12745
  id
12649
- });
12746
+ }, read);
12650
12747
  }
12651
12748
  /**
12652
12749
  * Record which collection a request is about, before anything can fail.
@@ -13301,7 +13398,7 @@ var RestApiGenerator = class RestApiGenerator {
13301
13398
  });
13302
13399
  const driver = this.getScopedDriver(c);
13303
13400
  const read = await RestApiGenerator.readRow(driver, ownRow(table.slug), String(id), queryOptions);
13304
- if (!read) throw this.entityNotFound(table.slug, String(id));
13401
+ if (!read) throw this.entityNotFound(table.slug, String(id), true);
13305
13402
  if (read.etag) c.header(ETAG_HEADER, read.etag);
13306
13403
  const body = projectResponseFields([read.row], queryOptions.fields, table, { include: queryOptions.include })[0];
13307
13404
  return c.json(body);
@@ -13596,7 +13693,7 @@ var RestApiGenerator = class RestApiGenerator {
13596
13693
  else if (parsed.id) {
13597
13694
  const queryOptions = this.parseQuery(c.req.queries(), nestedAccess);
13598
13695
  const read = await RestApiGenerator.readRow(driver, nestedRow(nested), parsed.id, queryOptions);
13599
- if (!read) throw this.entityNotFound(nested.path, parsed.id);
13696
+ if (!read) throw this.entityNotFound(nested.path, parsed.id, true);
13600
13697
  if (read.etag) c.header(ETAG_HEADER, read.etag);
13601
13698
  return c.json(projectResponseFields([read.row], queryOptions.fields, nestedTable.table, { include: queryOptions.include })[0]);
13602
13699
  } else return this.listRows(c, nestedTable, c.req.queries(), nested.path);
@@ -17876,11 +17973,11 @@ async function createStorageController(config) {
17876
17973
  switch (config.type) {
17877
17974
  case "local": return new LocalStorageController(config);
17878
17975
  case "s3": {
17879
- const { S3StorageController } = await import("./S3StorageController-DDAq8Kt5.js").then((n) => n.n);
17976
+ const { S3StorageController } = await import("./S3StorageController-C9LjuMhL.js").then((n) => n.n);
17880
17977
  return new S3StorageController(config);
17881
17978
  }
17882
17979
  case "gcs": {
17883
- const { GCSStorageController } = await import("./GCSStorageController-sCw2c4aA.js").then((n) => n.n);
17980
+ const { GCSStorageController } = await import("./GCSStorageController-B3p3aUX-.js").then((n) => n.n);
17884
17981
  return new GCSStorageController(config);
17885
17982
  }
17886
17983
  default: throw new Error(`Unknown storage type: ${config.type}. Built-in types: local, s3, gcs. For other providers, implement the StorageController interface directly.`);
@@ -18122,7 +18219,7 @@ function noCollectionsCause(unprotected) {
18122
18219
  * routes wherever and as often as the application asks.
18123
18220
  */
18124
18221
  async function loadOpenApiGenerator() {
18125
- const { generateOpenApiSpec } = await import("./openapi-generator-CoAFACMx.js").then((n) => n.r);
18222
+ const { generateOpenApiSpec } = await import("./openapi-generator-CAhJiwBm.js").then((n) => n.r);
18126
18223
  return generateOpenApiSpec;
18127
18224
  }
18128
18225
  /**
@@ -22188,8 +22285,8 @@ function createDeviceLoginStore(driver, options = {}) {
22188
22285
  requestIp: String(row.request_ip),
22189
22286
  requestUserAgent: String(row.request_user_agent),
22190
22287
  status: toStatus(row.status),
22191
- createdAt: toDate(row.created_at),
22192
- expiresAt: toDate(row.expires_at),
22288
+ createdAt: toDate$1(row.created_at),
22289
+ expiresAt: toDate$1(row.expires_at),
22193
22290
  expired: row.expired === true
22194
22291
  };
22195
22292
  },
@@ -22238,7 +22335,7 @@ function createDeviceLoginStore(driver, options = {}) {
22238
22335
  function toStatus(value) {
22239
22336
  return value === "approved" || value === "denied" || value === "consumed" ? value : "pending";
22240
22337
  }
22241
- function toDate(value) {
22338
+ function toDate$1(value) {
22242
22339
  return value instanceof Date ? value : new Date(String(value));
22243
22340
  }
22244
22341
  //#endregion
@@ -24041,7 +24138,7 @@ var VISIBLE = `(owner_id = $1 OR visibility = 'team' OR (visibility = 'roles' AN
24041
24138
  * Postgres's own text (`2026-11-09 17:02:23.6+01`), which not every browser
24042
24139
  * parses; JSON's rendering of it is ISO in every driver.
24043
24140
  */
24044
- var COLUMNS = "id, title, collections, visibility, roles, owner_id, to_json(created_at) #>> '{}' AS created_at, to_json(updated_at) #>> '{}' AS updated_at";
24141
+ var COLUMNS$1 = "id, title, collections, visibility, roles, owner_id, to_json(created_at) #>> '{}' AS created_at, to_json(updated_at) #>> '{}' AS updated_at";
24045
24142
  /** The longest app one person saves, in characters: any signed-in user may save, so the store is bounded per app too. */
24046
24143
  var MAX_APP_CODE_LENGTH = 256e3;
24047
24144
  var stores = /* @__PURE__ */ new WeakMap();
@@ -24084,12 +24181,12 @@ function createSavedAppStore(exec) {
24084
24181
  return {
24085
24182
  async list(viewer) {
24086
24183
  await ensure();
24087
- return (await exec(`SELECT ${COLUMNS} FROM ${TABLE} WHERE ${VISIBLE} ORDER BY updated_at DESC LIMIT 200`, { params: visibleTo(viewer) }) ?? []).map(summaryOf);
24184
+ return (await exec(`SELECT ${COLUMNS$1} FROM ${TABLE} WHERE ${VISIBLE} ORDER BY updated_at DESC LIMIT 200`, { params: visibleTo(viewer) }) ?? []).map(summaryOf);
24088
24185
  },
24089
24186
  async get(id, viewer) {
24090
24187
  if (!isUuid(id)) return void 0;
24091
24188
  await ensure();
24092
- const row = (await exec(`SELECT ${COLUMNS}, code FROM ${TABLE} WHERE id = $3 AND ${VISIBLE}`, { params: [...visibleTo(viewer), id] }))?.[0];
24189
+ const row = (await exec(`SELECT ${COLUMNS$1}, code FROM ${TABLE} WHERE id = $3 AND ${VISIBLE}`, { params: [...visibleTo(viewer), id] }))?.[0];
24093
24190
  return row ? appOf(row) : void 0;
24094
24191
  },
24095
24192
  async save(input, viewer) {
@@ -24103,7 +24200,7 @@ function createSavedAppStore(exec) {
24103
24200
  const row = (await exec(`
24104
24201
  UPDATE ${TABLE} SET title = $1, code = $2, collections = $3::text[], visibility = $4, roles = $5::text[], updated_at = now()
24105
24202
  WHERE id = $6 AND (owner_id = $7 OR $8)
24106
- RETURNING ${COLUMNS}, code`, { params: [
24203
+ RETURNING ${COLUMNS$1}, code`, { params: [
24107
24204
  input.title,
24108
24205
  input.code,
24109
24206
  input.collections,
@@ -24121,7 +24218,7 @@ function createSavedAppStore(exec) {
24121
24218
  const row = (await exec(`
24122
24219
  INSERT INTO ${TABLE} (title, code, collections, visibility, roles, owner_id)
24123
24220
  VALUES ($1, $2, $3::text[], $4, $5::text[], $6)
24124
- RETURNING ${COLUMNS}, code`, { params: [
24221
+ RETURNING ${COLUMNS$1}, code`, { params: [
24125
24222
  input.title,
24126
24223
  input.code,
24127
24224
  input.collections,
@@ -27166,13 +27263,17 @@ function loadBundle(bundleDir) {
27166
27263
  staticApps: (entry.static ?? []).map((item) => {
27167
27264
  const host = readStaticAppHost(item);
27168
27265
  refuseReservedStaticPath(item);
27266
+ const routes = readStaticAppRoutes(item);
27267
+ const frameAncestors = readStaticAppFrameAncestors(item);
27169
27268
  const resolved = resolveEntry(item.dir, `static app "${item.path}"`);
27170
27269
  if (!resolved) return void 0;
27171
27270
  return {
27172
27271
  path: item.path,
27173
27272
  ...host !== void 0 ? { host } : {},
27174
27273
  dir: resolved,
27175
- spa: item.spa !== false
27274
+ spa: item.spa !== false,
27275
+ ...routes ? { routes } : {},
27276
+ ...frameAncestors ? { frameAncestors } : {}
27176
27277
  };
27177
27278
  }).filter((item) => item !== void 0).sort(compareStaticApps)
27178
27279
  };
@@ -27207,6 +27308,54 @@ function readStaticAppHost(item) {
27207
27308
  throw new BundleError(`Static app "${item.name ?? path$1.basename(item.dir)}" (at ${item.path}) declares host ${JSON.stringify(host)}, which is not a hostname this runtime can serve it on.`, "A static app's host is a lowercase public DNS name such as \"admin.example.com\" — no scheme, port or path. Fix the app's `path` in rebase.json and rebuild with `rebase build`.");
27208
27309
  }
27209
27310
  /**
27311
+ * Read a static app's routes, refusing one the CLI would have refused.
27312
+ *
27313
+ * Refused rather than dropped, for the reason a bad `host` is: the CLI and
27314
+ * this check are the same function (`validateStaticRoute`), so a bundle
27315
+ * carrying a bad route was written by something else, and a route quietly
27316
+ * skipped is a path answered by the app's `index.html` instead of its
27317
+ * function. Absent, or an empty list, is `undefined`.
27318
+ */
27319
+ function readStaticAppRoutes(item) {
27320
+ const routes = item.routes;
27321
+ if (routes === void 0) return void 0;
27322
+ const name = item.name ?? path$1.basename(item.dir);
27323
+ const refuse = (problem) => {
27324
+ throw new BundleError(`Static app "${name}" (at ${item.path}) declares ${problem}`, "Fix the app's `routes` in rebase.json and rebuild with `rebase build`.");
27325
+ };
27326
+ if (!Array.isArray(routes)) return refuse(`routes that are not a list: ${JSON.stringify(routes)}.`);
27327
+ const valid = routes.map((route) => {
27328
+ const result = validateStaticRoute(route, item.path);
27329
+ if (!result.ok) return refuse(`a route this runtime cannot serve, ${JSON.stringify(route)}: ${result.field ? `its ${result.field}` : "it"} ${result.reason}.`);
27330
+ return result.route;
27331
+ });
27332
+ return valid.length > 0 ? valid : void 0;
27333
+ }
27334
+ /**
27335
+ * Read the origins a static app may be framed by, refusing anything that is
27336
+ * not exactly one origin.
27337
+ *
27338
+ * Each value is written into a `Content-Security-Policy` header, so this is
27339
+ * the check that keeps a bundle from adding directives to it. Refused, not
27340
+ * dropped: an app whose list is ignored is an app its CMS cannot preview, and
27341
+ * the boot is the only place left to say why.
27342
+ */
27343
+ function readStaticAppFrameAncestors(item) {
27344
+ const origins = item.frameAncestors;
27345
+ if (origins === void 0) return void 0;
27346
+ const name = item.name ?? path$1.basename(item.dir);
27347
+ const refuse = (problem) => {
27348
+ throw new BundleError(`Static app "${name}" (at ${item.path}) declares frameAncestors ${problem}`, "Fix the app's `frameAncestors` in rebase.json and rebuild with `rebase build`.");
27349
+ };
27350
+ if (!Array.isArray(origins)) return refuse(`that is not a list: ${JSON.stringify(origins)}.`);
27351
+ const valid = origins.map((origin) => {
27352
+ const result = parseFrameAncestor(origin);
27353
+ if (!result.ok) return refuse(`with ${JSON.stringify(origin)}, which ${result.reason}.`);
27354
+ return result.origin;
27355
+ });
27356
+ return valid.length > 0 ? valid : void 0;
27357
+ }
27358
+ /**
27210
27359
  * Import the bundle's Drizzle schema module, for the boot-time staleness check.
27211
27360
  *
27212
27361
  * Returns `undefined` when the bundle declares none, and that is not a
@@ -28200,6 +28349,856 @@ function createQueueRuntime(options) {
28200
28349
  } };
28201
28350
  }
28202
28351
  //#endregion
28352
+ //#region src/dev-secrets.ts
28353
+ /**
28354
+ * Development secrets that survive a restart.
28355
+ *
28356
+ * `loadEnv` generates `JWT_SECRET` and `REBASE_SERVICE_KEY` when they are unset
28357
+ * outside production, so a developer can start without setting anything up. It
28358
+ * generated them **freshly on every boot**, which meant every restart of the dev
28359
+ * server silently invalidated the previous run's tokens: you were logged out of
28360
+ * your own app because you edited a file, and the API key you had just made
28361
+ * stopped working.
28362
+ *
28363
+ * The CLI already worked around it for scaffolded projects by writing a stable
28364
+ * `JWT_SECRET` into `.env` at `rebase init` — the comment there says exactly
28365
+ * why. That leaves anyone who did not scaffold, and anyone running from a
28366
+ * container with no `.env`, with the logout-on-restart behaviour.
28367
+ *
28368
+ * So the generated values are cached in a file beside the other dev-state
28369
+ * files — `.rebase-dev-port` and `.rebase-dev-url` follow the same convention
28370
+ * and are gitignored in the same place.
28371
+ *
28372
+ * ## What this does not change
28373
+ *
28374
+ * Production. `loadEnv` refuses to start when a secret was auto-generated and
28375
+ * `NODE_ENV=production`, and that is untouched: this only makes the
28376
+ * already-generated development values stable. There is no path by which a
28377
+ * cached secret becomes a production one.
28378
+ *
28379
+ * ## Failing soft
28380
+ *
28381
+ * A read-only filesystem, a container without a writable working directory, a
28382
+ * permissions problem — none of these should stop a development server from
28383
+ * starting. Every failure here falls back to the previous behaviour, an
28384
+ * ephemeral secret, and says so once at debug level.
28385
+ */
28386
+ /** Beside `.rebase-dev-port` and `.rebase-dev-url`, and gitignored with them. */
28387
+ var DEV_SECRETS_FILENAME = ".rebase-dev-secrets.json";
28388
+ /** Owner read/write only. These are secrets, even development ones. */
28389
+ var FILE_MODE = 384;
28390
+ /** Whether these environment variables describe a test runner. */
28391
+ function detectTestRunner(env) {
28392
+ return Boolean(env.JEST_WORKER_ID || env.VITEST || env.VITEST_WORKER_ID || env.NODE_ENV === "test");
28393
+ }
28394
+ /**
28395
+ * Whether a test runner started this process, decided **once at import**.
28396
+ *
28397
+ * Read at call time it would be wrong, and provably so: `env.test.ts` does
28398
+ * `process.env = {}` in its `beforeEach`, which erases `NODE_ENV` and
28399
+ * `JEST_WORKER_ID` alike. A predicate consulting the live environment therefore
28400
+ * sees a bare object and concludes "development", which is how the first version
28401
+ * of this dropped a `.rebase-dev-secrets.json` into `packages/server` on every
28402
+ * test run.
28403
+ *
28404
+ * Whether a test runner is hosting the process is a fact about the process, not
28405
+ * about whatever a test has since done to `process.env`, so it is captured
28406
+ * before any test can rewrite it.
28407
+ */
28408
+ var TEST_RUNNER_DETECTED = detectTestRunner(process.env);
28409
+ /**
28410
+ * Whether generated secrets should be cached at all.
28411
+ *
28412
+ * Not in production — `loadEnv` refuses to boot there on a generated secret, so
28413
+ * there is nothing to cache and no path by which a cached one becomes a
28414
+ * production one.
28415
+ *
28416
+ * Not under a test runner: a test must not inherit a secret a previous run left
28417
+ * behind, and a library call has no business writing into a suite's working
28418
+ * directory. `inTestRunner` is a parameter only so this predicate can be tested
28419
+ * on its own; callers pass nothing.
28420
+ */
28421
+ function shouldCacheDevSecrets(env = process.env, inTestRunner = TEST_RUNNER_DETECTED) {
28422
+ if (inTestRunner) return false;
28423
+ return env.NODE_ENV !== "production";
28424
+ }
28425
+ /** `REBASE_DEV_SECRETS_FILE`, or the conventional name in the working directory. */
28426
+ function resolveDevSecretsFile(env = process.env) {
28427
+ const override = env.REBASE_DEV_SECRETS_FILE?.trim();
28428
+ if (override) return path$3.resolve(override);
28429
+ return path$3.join(process.cwd(), DEV_SECRETS_FILENAME);
28430
+ }
28431
+ /**
28432
+ * Open the cache.
28433
+ *
28434
+ * Reading a malformed file is treated as an empty cache rather than an error:
28435
+ * the file is ours, it holds regenerable values, and refusing to boot over a
28436
+ * corrupted convenience cache would be worse than rewriting it.
28437
+ */
28438
+ function openDevSecretStore(file = resolveDevSecretsFile()) {
28439
+ let cache = {};
28440
+ let usable = true;
28441
+ try {
28442
+ if (fs$3.existsSync(file)) {
28443
+ const parsed = JSON.parse(fs$3.readFileSync(file, "utf-8"));
28444
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
28445
+ for (const [key, value] of Object.entries(parsed)) if (typeof value === "string" && value.length > 0) cache[key] = value;
28446
+ }
28447
+ }
28448
+ } catch {
28449
+ cache = {};
28450
+ }
28451
+ const flush = () => {
28452
+ try {
28453
+ fs$3.mkdirSync(path$3.dirname(file), { recursive: true });
28454
+ fs$3.writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`, { mode: FILE_MODE });
28455
+ fs$3.chmodSync(file, FILE_MODE);
28456
+ } catch (err) {
28457
+ if (usable) {
28458
+ usable = false;
28459
+ logger.debug(`[dev-secrets] Could not write ${file}, so generated development secrets will not survive a restart: ${err instanceof Error ? err.message : String(err)}`);
28460
+ }
28461
+ }
28462
+ };
28463
+ return {
28464
+ file,
28465
+ get usable() {
28466
+ return usable;
28467
+ },
28468
+ get: (name) => cache[name],
28469
+ set: (name, value) => {
28470
+ cache[name] = value;
28471
+ flush();
28472
+ }
28473
+ };
28474
+ }
28475
+ //#endregion
28476
+ //#region src/push/web-push-crypto.ts
28477
+ /**
28478
+ * The two pieces of cryptography Web Push needs, on `node:crypto` alone:
28479
+ *
28480
+ * - **VAPID** (RFC 8292): a short-lived ES256 JWT that tells the push service
28481
+ * which application server is sending, so a subscription made with this
28482
+ * server's public key only accepts messages signed by its private key.
28483
+ * - **Message encryption** (RFC 8291, `aes128gcm` from RFC 8188): the payload
28484
+ * is encrypted to the browser's own key, so the push service carries it
28485
+ * without being able to read it.
28486
+ *
28487
+ * Both are small and fully specified, and RFC 8291 Appendix A gives a complete
28488
+ * worked example, which `web-push-crypto.test.ts` reproduces byte for byte.
28489
+ */
28490
+ /** The record size every message is written with: one record, the RFC's own value. */
28491
+ var RECORD_SIZE = 4096;
28492
+ /** salt (16) + rs (4) + idlen (1) + the sender's public key (65). */
28493
+ var HEADER_LENGTH = 86;
28494
+ /**
28495
+ * The largest plaintext one record can carry: the record size less the header,
28496
+ * the tag and the one-byte delimiter. Push services refuse bodies over 4096
28497
+ * bytes, so this is also the practical limit.
28498
+ */
28499
+ var MAX_PAYLOAD_BYTES = RECORD_SIZE - HEADER_LENGTH - 16 - 1;
28500
+ function toBase64Url(bytes) {
28501
+ return Buffer.from(bytes).toString("base64url");
28502
+ }
28503
+ /** Decode base64url, tolerating standard base64 and `=` padding, as browsers and libraries vary. */
28504
+ function fromBase64Url(text) {
28505
+ return Buffer.from(text.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_"), "base64url");
28506
+ }
28507
+ /** A new VAPID key pair. */
28508
+ function generateVapidKeys() {
28509
+ const ecdh = createECDH("prime256v1");
28510
+ ecdh.generateKeys();
28511
+ return {
28512
+ publicKey: toBase64Url(ecdh.getPublicKey()),
28513
+ privateKey: toBase64Url(leftPad(ecdh.getPrivateKey(), 32))
28514
+ };
28515
+ }
28516
+ /**
28517
+ * Whether a key pair is well formed and its halves belong together. Checked at
28518
+ * boot, because a mismatched pair is accepted by every push service at
28519
+ * subscribe time and refused at every send.
28520
+ */
28521
+ function validateVapidKeys(keys) {
28522
+ const publicKey = fromBase64Url(keys.publicKey);
28523
+ const privateKey = fromBase64Url(keys.privateKey);
28524
+ if (publicKey.length !== 65 || publicKey[0] !== 4) return "the public key is not an uncompressed P-256 point (65 bytes, base64url)";
28525
+ if (privateKey.length !== 32) return "the private key is not 32 bytes (base64url)";
28526
+ try {
28527
+ const ecdh = createECDH("prime256v1");
28528
+ ecdh.setPrivateKey(privateKey);
28529
+ if (!ecdh.getPublicKey().equals(publicKey)) return "the public key does not belong to the private key";
28530
+ } catch {
28531
+ return "the private key is not a valid P-256 key";
28532
+ }
28533
+ return null;
28534
+ }
28535
+ function leftPad(bytes, length) {
28536
+ return bytes.length >= length ? bytes : Buffer.concat([Buffer.alloc(length - bytes.length), bytes]);
28537
+ }
28538
+ function signingKey(keys) {
28539
+ const publicKey = fromBase64Url(keys.publicKey);
28540
+ return createPrivateKey({
28541
+ key: {
28542
+ kty: "EC",
28543
+ crv: "P-256",
28544
+ d: toBase64Url(fromBase64Url(keys.privateKey)),
28545
+ x: toBase64Url(publicKey.subarray(1, 33)),
28546
+ y: toBase64Url(publicKey.subarray(33, 65))
28547
+ },
28548
+ format: "jwk"
28549
+ });
28550
+ }
28551
+ /**
28552
+ * The `Authorization` header for one push service: `vapid t=<jwt>, k=<key>`.
28553
+ *
28554
+ * `aud` is the push service's origin and `exp` is at most 24 hours ahead (the
28555
+ * RFC's ceiling); twelve leaves room for clock skew.
28556
+ */
28557
+ function vapidAuthorization(endpoint, keys, subject, now = /* @__PURE__ */ new Date()) {
28558
+ const header = toBase64Url(Buffer.from(JSON.stringify({
28559
+ typ: "JWT",
28560
+ alg: "ES256"
28561
+ })));
28562
+ const claims = toBase64Url(Buffer.from(JSON.stringify({
28563
+ aud: new URL(endpoint).origin,
28564
+ exp: Math.floor(now.getTime() / 1e3) + 720 * 60,
28565
+ sub: subject
28566
+ })));
28567
+ return `vapid t=${header}.${claims}.${toBase64Url(sign("sha256", Buffer.from(`${header}.${claims}`), {
28568
+ key: signingKey(keys),
28569
+ dsaEncoding: "ieee-p1363"
28570
+ }))}, k=${keys.publicKey}`;
28571
+ }
28572
+ function hmac(key, data) {
28573
+ return createHmac("sha256", key).update(data).digest();
28574
+ }
28575
+ /**
28576
+ * Encrypt `plaintext` to one browser: the `aes128gcm` body, header included.
28577
+ *
28578
+ * Throws when the plaintext does not fit in one record — the caller's payload
28579
+ * is too big for Web Push and nothing can deliver it.
28580
+ */
28581
+ function encryptPayload(plaintext, p256dh, auth, fixture) {
28582
+ if (plaintext.length > 3993) throw new Error(`push: the payload is ${plaintext.length} bytes; Web Push carries at most ${MAX_PAYLOAD_BYTES}.`);
28583
+ const receiverPublicKey = fromBase64Url(p256dh);
28584
+ const authSecret = fromBase64Url(auth);
28585
+ const sender = createECDH("prime256v1");
28586
+ if (fixture) sender.setPrivateKey(fixture.senderPrivateKey);
28587
+ else sender.generateKeys();
28588
+ const senderPublicKey = sender.getPublicKey();
28589
+ const salt = fixture?.salt ?? randomBytes(16);
28590
+ const prkKey = hmac(authSecret, sender.computeSecret(receiverPublicKey));
28591
+ const keyInfo = Buffer.concat([
28592
+ Buffer.from("WebPush: info\0"),
28593
+ receiverPublicKey,
28594
+ senderPublicKey
28595
+ ]);
28596
+ const prk = hmac(salt, hmac(prkKey, Buffer.concat([keyInfo, Buffer.from([1])])));
28597
+ const cipher = createCipheriv("aes-128-gcm", hmac(prk, Buffer.from("Content-Encoding: aes128gcm\0")).subarray(0, 16), hmac(prk, Buffer.from("Content-Encoding: nonce\0")).subarray(0, 12));
28598
+ const ciphertext = Buffer.concat([
28599
+ cipher.update(Buffer.concat([plaintext, Buffer.from([2])])),
28600
+ cipher.final(),
28601
+ cipher.getAuthTag()
28602
+ ]);
28603
+ const header = Buffer.alloc(HEADER_LENGTH);
28604
+ salt.copy(header, 0);
28605
+ header.writeUInt32BE(RECORD_SIZE, 16);
28606
+ header.writeUInt8(senderPublicKey.length, 20);
28607
+ senderPublicKey.copy(header, 21);
28608
+ return Buffer.concat([header, ciphertext]);
28609
+ }
28610
+ //#endregion
28611
+ //#region src/push/subscription-input.ts
28612
+ /**
28613
+ * What a browser sends when it subscribes, checked before anything is stored.
28614
+ *
28615
+ * The endpoint is the part that matters for security. The server posts to
28616
+ * whatever address a subscription names, every time it sends, so an endpoint
28617
+ * is a URL an attacker chooses and this server fetches — server-side request
28618
+ * forgery with a retry loop. Only the push services browsers actually use are
28619
+ * accepted: https, on their own hostnames, on the default port.
28620
+ */
28621
+ /**
28622
+ * The push services of Chrome and Android (FCM), Firefox (Mozilla autopush),
28623
+ * Safari on iOS, iPadOS and macOS (Apple), and Edge (Windows Push Notification
28624
+ * Services).
28625
+ */
28626
+ var PUSH_SERVICE_HOSTS = [
28627
+ /^fcm\.googleapis\.com$/,
28628
+ /^android\.googleapis\.com$/,
28629
+ /^updates\.push\.services\.mozilla\.com$/,
28630
+ /^web\.push\.apple\.com$/,
28631
+ /^[a-z0-9-]+\.push\.apple\.com$/,
28632
+ /^[a-z0-9-]+\.notify\.windows\.com$/
28633
+ ];
28634
+ /** The longest endpoint taken. Real ones run to a few hundred characters. */
28635
+ var MAX_ENDPOINT_LENGTH = 1024;
28636
+ /**
28637
+ * The endpoint, normalised, when it is on a known push service or one of
28638
+ * `extraHosts` (exact hostnames; these may name a port, for a local test push
28639
+ * service). `null` otherwise.
28640
+ */
28641
+ function acceptEndpoint(value, extraHosts = []) {
28642
+ if (typeof value !== "string" || value.length > MAX_ENDPOINT_LENGTH) return null;
28643
+ let url;
28644
+ try {
28645
+ url = new URL(value);
28646
+ } catch {
28647
+ return null;
28648
+ }
28649
+ if (url.protocol !== "https:" || url.username || url.password) return null;
28650
+ if (extraHosts.includes(url.host) || extraHosts.includes(url.hostname)) return url.href;
28651
+ if (url.port !== "") return null;
28652
+ return PUSH_SERVICE_HOSTS.some((pattern) => pattern.test(url.hostname)) ? url.href : null;
28653
+ }
28654
+ /** The browser's P-256 public key: base64url of an uncompressed point. */
28655
+ function acceptP256dh(value) {
28656
+ if (typeof value !== "string" || value.length > 120 || !/^[A-Za-z0-9_\-+/]+={0,2}$/.test(value)) return null;
28657
+ const bytes = fromBase64Url(value);
28658
+ return bytes.length === 65 && bytes[0] === 4 ? value : null;
28659
+ }
28660
+ /** The browser's auth secret: base64url of 16 bytes. */
28661
+ function acceptAuthSecret(value) {
28662
+ if (typeof value !== "string" || value.length > 40 || !/^[A-Za-z0-9_\-+/]+={0,2}$/.test(value)) return null;
28663
+ return fromBase64Url(value).length === 16 ? value : null;
28664
+ }
28665
+ /** A BCP 47-ish language tag (`en`, `es`, `pt-BR`), or `null`. */
28666
+ function acceptLang(value) {
28667
+ if (typeof value !== "string" || value.length > 35) return null;
28668
+ return /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/.test(value) ? value : null;
28669
+ }
28670
+ /**
28671
+ * A subscription's id: the first 24 characters of the endpoint's SHA-256, in
28672
+ * base64url. Endpoints are hundreds of characters, and the id is what an
28673
+ * application keys its own per-browser rows by.
28674
+ */
28675
+ function subscriptionIdOf(endpoint) {
28676
+ return createHash("sha256").update(endpoint).digest("base64url").slice(0, 24);
28677
+ }
28678
+ /** A topic the push services take: up to 32 URL-safe base64 characters. */
28679
+ function isValidTopic(topic) {
28680
+ return /^[A-Za-z0-9_-]{1,32}$/.test(topic);
28681
+ }
28682
+ //#endregion
28683
+ //#region src/push/push-service.ts
28684
+ /** A day: long enough for a phone that was off overnight. */
28685
+ var DEFAULT_TTL_SECONDS = 86400;
28686
+ /** Push services hold a message for four weeks at most. */
28687
+ var MAX_TTL_SECONDS = 2419200;
28688
+ var URGENCIES = /* @__PURE__ */ new Set([
28689
+ "very-low",
28690
+ "low",
28691
+ "normal",
28692
+ "high"
28693
+ ]);
28694
+ /** Sends in flight at once, so a send to thousands of browsers does not open thousands of sockets. */
28695
+ var CONCURRENCY = 16;
28696
+ function resolveOptions(options = {}) {
28697
+ const ttl = options.ttl ?? DEFAULT_TTL_SECONDS;
28698
+ if (!Number.isInteger(ttl) || ttl < 0 || ttl > MAX_TTL_SECONDS) throw new Error(`push: ttl must be a whole number of seconds from 0 to ${MAX_TTL_SECONDS}; got ${String(options.ttl)}.`);
28699
+ const urgency = options.urgency ?? "normal";
28700
+ if (!URGENCIES.has(urgency)) throw new Error(`push: urgency must be "very-low", "low", "normal" or "high"; got ${JSON.stringify(urgency)}.`);
28701
+ if (options.topic !== void 0 && !isValidTopic(options.topic)) throw new Error(`push: topic must be 1 to 32 characters of A-Z, a-z, 0-9, "-" and "_"; got ${JSON.stringify(options.topic)}.`);
28702
+ return {
28703
+ ttl,
28704
+ urgency,
28705
+ topic: options.topic,
28706
+ tag: options.tag
28707
+ };
28708
+ }
28709
+ /** Run `work` over `items`, at most `limit` at a time. */
28710
+ async function eachLimited(items, limit, work) {
28711
+ let next = 0;
28712
+ const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
28713
+ while (next < items.length) await work(items[next++]);
28714
+ });
28715
+ await Promise.all(lanes);
28716
+ }
28717
+ function createPushService({ store, sender, publicKey }) {
28718
+ const deliver = async (subscriptions, input, options) => {
28719
+ const how = resolveOptions(options);
28720
+ const messages = subscriptions.map((subscription) => {
28721
+ const payload = typeof input === "function" ? input(subscription.info) : input;
28722
+ const text = JSON.stringify(how.tag === void 0 ? payload : {
28723
+ ...payload,
28724
+ tag: how.tag
28725
+ });
28726
+ const bytes = Buffer.byteLength(text, "utf8");
28727
+ if (bytes > 3993) throw new Error(`push: the payload is ${bytes} bytes as JSON; Web Push carries at most ${MAX_PAYLOAD_BYTES}.`);
28728
+ return {
28729
+ subscription,
28730
+ text
28731
+ };
28732
+ });
28733
+ const result = {
28734
+ sent: 0,
28735
+ removed: 0,
28736
+ failed: 0
28737
+ };
28738
+ const delivered = [];
28739
+ await eachLimited(messages, CONCURRENCY, async ({ subscription, text }) => {
28740
+ const { info } = subscription;
28741
+ try {
28742
+ const answer = await sender.send(subscription, text, {
28743
+ ttl: how.ttl,
28744
+ urgency: how.urgency,
28745
+ topic: how.topic
28746
+ });
28747
+ if (answer.statusCode >= 200 && answer.statusCode < 300) {
28748
+ result.sent++;
28749
+ delivered.push(info.id);
28750
+ } else if (answer.statusCode === 404 || answer.statusCode === 410) {
28751
+ result.removed++;
28752
+ await store.removeGone(info.id, subscription.p256dh);
28753
+ logger.debug("[push] a subscription is gone; removed", {
28754
+ id: info.id,
28755
+ status: answer.statusCode,
28756
+ host: info.endpointHost
28757
+ });
28758
+ } else {
28759
+ result.failed++;
28760
+ logger.warn("[push] the push service refused a message", {
28761
+ id: info.id,
28762
+ host: info.endpointHost,
28763
+ status: answer.statusCode,
28764
+ body: answer.body
28765
+ });
28766
+ }
28767
+ } catch (error) {
28768
+ result.failed++;
28769
+ logger.warn("[push] could not reach the push service", {
28770
+ id: info.id,
28771
+ host: info.endpointHost,
28772
+ error
28773
+ });
28774
+ }
28775
+ });
28776
+ if (delivered.length > 0) await store.markSent(delivered).catch((error) => logger.debug("[push] could not record last_sent_at", { error }));
28777
+ return result;
28778
+ };
28779
+ return {
28780
+ isConfigured: () => true,
28781
+ publicKey: () => publicKey,
28782
+ async sendToUser(userId, payload, options) {
28783
+ return deliver(await store.listForUser(userId), payload, options);
28784
+ },
28785
+ async sendToSubscriptions(ids, payload, options) {
28786
+ return deliver(await store.listByIds(ids), payload, options);
28787
+ },
28788
+ async subscriptionsOf(userId) {
28789
+ return (await store.listForUser(userId)).map((s) => s.info);
28790
+ }
28791
+ };
28792
+ }
28793
+ /**
28794
+ * `rebase.push` on a backend where push cannot send: off, or without keys.
28795
+ * Every call that would send throws `reason`, which names what to set.
28796
+ */
28797
+ function createUnconfiguredPushService(reason) {
28798
+ const refuse = () => {
28799
+ throw new Error(reason);
28800
+ };
28801
+ return {
28802
+ isConfigured: () => false,
28803
+ publicKey: () => null,
28804
+ sendToUser: async () => refuse(),
28805
+ sendToSubscriptions: async () => refuse(),
28806
+ subscriptionsOf: async () => refuse()
28807
+ };
28808
+ }
28809
+ //#endregion
28810
+ //#region src/push/push-store.ts
28811
+ var PUSH_SUBSCRIPTIONS_TABLE = "rebase.push_subscriptions";
28812
+ var COLUMNS = "id, user_id, endpoint, p256dh, auth, lang, created_at, last_sent_at";
28813
+ function toDate(value) {
28814
+ return value instanceof Date ? value : new Date(String(value));
28815
+ }
28816
+ function toStored(row) {
28817
+ const endpoint = String(row.endpoint);
28818
+ let endpointHost = "";
28819
+ try {
28820
+ endpointHost = new URL(endpoint).host;
28821
+ } catch {}
28822
+ return {
28823
+ endpoint,
28824
+ p256dh: String(row.p256dh),
28825
+ auth: String(row.auth),
28826
+ info: {
28827
+ id: String(row.id),
28828
+ userId: String(row.user_id),
28829
+ endpointHost,
28830
+ lang: row.lang == null ? null : String(row.lang),
28831
+ createdAt: toDate(row.created_at),
28832
+ lastSentAt: row.last_sent_at == null ? null : toDate(row.last_sent_at)
28833
+ }
28834
+ };
28835
+ }
28836
+ /**
28837
+ * The request roles may read and delete their own rows, and nothing else: the
28838
+ * schema-wide grant gives them full DML on every table created later, so the
28839
+ * insert and update rights are taken back explicitly.
28840
+ */
28841
+ var REQUEST_ROLE_GRANTS_SQL = `
28842
+ DO $rebase_push_grants$
28843
+ DECLARE
28844
+ request_roles text[];
28845
+ request_role text;
28846
+ BEGIN
28847
+ ${LOAD_REQUEST_ROLES_PLPGSQL}
28848
+ FOREACH request_role IN ARRAY request_roles LOOP
28849
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role) THEN
28850
+ EXECUTE format('REVOKE ALL ON ${PUSH_SUBSCRIPTIONS_TABLE} FROM %I', request_role);
28851
+ EXECUTE format('GRANT SELECT, DELETE ON ${PUSH_SUBSCRIPTIONS_TABLE} TO %I', request_role);
28852
+ END IF;
28853
+ END LOOP;
28854
+ END
28855
+ $rebase_push_grants$`;
28856
+ /** Own rows only. Guarded on `rebase.uid()`, which the RLS bootstrap creates. */
28857
+ var POLICIES_SQL = `
28858
+ DO $rebase_push_policies$
28859
+ BEGIN
28860
+ IF to_regprocedure('rebase.uid()') IS NULL THEN
28861
+ RETURN;
28862
+ END IF;
28863
+ IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'rebase' AND tablename = 'push_subscriptions' AND policyname = 'push_subscriptions_own_select') THEN
28864
+ CREATE POLICY push_subscriptions_own_select ON ${PUSH_SUBSCRIPTIONS_TABLE} FOR SELECT USING (user_id = rebase.uid());
28865
+ END IF;
28866
+ IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname = 'rebase' AND tablename = 'push_subscriptions' AND policyname = 'push_subscriptions_own_delete') THEN
28867
+ CREATE POLICY push_subscriptions_own_delete ON ${PUSH_SUBSCRIPTIONS_TABLE} FOR DELETE USING (user_id = rebase.uid());
28868
+ END IF;
28869
+ END
28870
+ $rebase_push_policies$`;
28871
+ function createPushStore(exec) {
28872
+ return {
28873
+ async ensure() {
28874
+ await exec(`
28875
+ CREATE TABLE IF NOT EXISTS ${PUSH_SUBSCRIPTIONS_TABLE} (
28876
+ id text PRIMARY KEY,
28877
+ user_id text NOT NULL,
28878
+ endpoint text NOT NULL,
28879
+ p256dh text NOT NULL,
28880
+ auth text NOT NULL,
28881
+ lang text,
28882
+ user_agent text,
28883
+ created_at timestamptz NOT NULL DEFAULT now(),
28884
+ updated_at timestamptz NOT NULL DEFAULT now(),
28885
+ last_sent_at timestamptz
28886
+ )`);
28887
+ await exec(`CREATE INDEX IF NOT EXISTS push_subscriptions_user_id ON ${PUSH_SUBSCRIPTIONS_TABLE} (user_id)`);
28888
+ await exec(`ALTER TABLE ${PUSH_SUBSCRIPTIONS_TABLE} ENABLE ROW LEVEL SECURITY`);
28889
+ await exec(POLICIES_SQL);
28890
+ await exec(REQUEST_ROLE_GRANTS_SQL);
28891
+ },
28892
+ async adopt() {
28893
+ try {
28894
+ await exec(`SELECT ${COLUMNS} FROM ${PUSH_SUBSCRIPTIONS_TABLE} WHERE false`);
28895
+ } catch (error) {
28896
+ throw new Error(`${PUSH_SUBSCRIPTIONS_TABLE} is missing or out of date, and this backend changes nothing in its database. Boot once with provisioning on to create it.`, { cause: error });
28897
+ }
28898
+ },
28899
+ async upsert(row) {
28900
+ await exec(`
28901
+ INSERT INTO ${PUSH_SUBSCRIPTIONS_TABLE} (id, user_id, endpoint, p256dh, auth, lang, user_agent)
28902
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
28903
+ ON CONFLICT (id) DO UPDATE SET
28904
+ created_at = CASE WHEN ${PUSH_SUBSCRIPTIONS_TABLE}.user_id = EXCLUDED.user_id THEN ${PUSH_SUBSCRIPTIONS_TABLE}.created_at ELSE now() END,
28905
+ last_sent_at = CASE WHEN ${PUSH_SUBSCRIPTIONS_TABLE}.user_id = EXCLUDED.user_id THEN ${PUSH_SUBSCRIPTIONS_TABLE}.last_sent_at ELSE NULL END,
28906
+ user_id = EXCLUDED.user_id,
28907
+ endpoint = EXCLUDED.endpoint,
28908
+ p256dh = EXCLUDED.p256dh,
28909
+ auth = EXCLUDED.auth,
28910
+ lang = EXCLUDED.lang,
28911
+ user_agent = EXCLUDED.user_agent,
28912
+ updated_at = now()`, [
28913
+ row.id,
28914
+ row.userId,
28915
+ row.endpoint,
28916
+ row.p256dh,
28917
+ row.auth,
28918
+ row.lang,
28919
+ row.userAgent
28920
+ ]);
28921
+ },
28922
+ async removeOwn(id, userId) {
28923
+ return (await exec(`DELETE FROM ${PUSH_SUBSCRIPTIONS_TABLE} WHERE id = $1 AND user_id = $2 RETURNING id`, [id, userId])).length > 0;
28924
+ },
28925
+ async removeGone(id, p256dh) {
28926
+ await exec(`DELETE FROM ${PUSH_SUBSCRIPTIONS_TABLE} WHERE id = $1 AND p256dh = $2`, [id, p256dh]);
28927
+ },
28928
+ async listForUser(userId) {
28929
+ return (await exec(`SELECT ${COLUMNS} FROM ${PUSH_SUBSCRIPTIONS_TABLE} WHERE user_id = $1 ORDER BY created_at`, [userId])).map(toStored);
28930
+ },
28931
+ async listByIds(ids) {
28932
+ if (ids.length === 0) return [];
28933
+ return (await exec(`SELECT ${COLUMNS} FROM ${PUSH_SUBSCRIPTIONS_TABLE} WHERE id = ANY($1::text[]) ORDER BY created_at`, [[...ids]])).map(toStored);
28934
+ },
28935
+ async markSent(ids) {
28936
+ if (ids.length === 0) return;
28937
+ await exec(`UPDATE ${PUSH_SUBSCRIPTIONS_TABLE} SET last_sent_at = now() WHERE id = ANY($1::text[])`, [[...ids]]);
28938
+ }
28939
+ };
28940
+ }
28941
+ //#endregion
28942
+ //#region src/push/vapid-config.ts
28943
+ var VAPID_PUBLIC_ENV = "REBASE_VAPID_PUBLIC_KEY";
28944
+ var VAPID_PRIVATE_ENV = "REBASE_VAPID_PRIVATE_KEY";
28945
+ var VAPID_SUBJECT_ENV = "REBASE_VAPID_SUBJECT";
28946
+ var HOW_TO_GENERATE = "Generate a pair with `npx web-push generate-vapid-keys`.";
28947
+ function resolveVapid(input) {
28948
+ const { env, isProduction } = input;
28949
+ let keys;
28950
+ let source = "options";
28951
+ if (input.vapid?.publicKey || input.vapid?.privateKey) {
28952
+ if (!input.vapid.publicKey || !input.vapid.privateKey) return {
28953
+ ok: false,
28954
+ reason: "push.vapid needs both publicKey and privateKey."
28955
+ };
28956
+ keys = {
28957
+ publicKey: input.vapid.publicKey,
28958
+ privateKey: input.vapid.privateKey
28959
+ };
28960
+ } else {
28961
+ const publicKey = env[VAPID_PUBLIC_ENV]?.trim();
28962
+ const privateKey = env[VAPID_PRIVATE_ENV]?.trim();
28963
+ if (publicKey || privateKey) {
28964
+ if (!publicKey || !privateKey) return {
28965
+ ok: false,
28966
+ reason: `Push needs both ${VAPID_PUBLIC_ENV} and ${VAPID_PRIVATE_ENV}; only one is set.`
28967
+ };
28968
+ keys = {
28969
+ publicKey,
28970
+ privateKey
28971
+ };
28972
+ source = "env";
28973
+ }
28974
+ }
28975
+ if (!keys) {
28976
+ if (isProduction) return {
28977
+ ok: false,
28978
+ reason: `Push is on but has no VAPID keys. Set ${VAPID_PUBLIC_ENV} and ${VAPID_PRIVATE_ENV} (and ${VAPID_SUBJECT_ENV}). ${HOW_TO_GENERATE}`
28979
+ };
28980
+ const cachedPublic = input.devStore?.get(VAPID_PUBLIC_ENV);
28981
+ const cachedPrivate = input.devStore?.get(VAPID_PRIVATE_ENV);
28982
+ if (cachedPublic && cachedPrivate && validateVapidKeys({
28983
+ publicKey: cachedPublic,
28984
+ privateKey: cachedPrivate
28985
+ }) === null) keys = {
28986
+ publicKey: cachedPublic,
28987
+ privateKey: cachedPrivate
28988
+ };
28989
+ else {
28990
+ keys = generateVapidKeys();
28991
+ input.devStore?.set(VAPID_PUBLIC_ENV, keys.publicKey);
28992
+ input.devStore?.set(VAPID_PRIVATE_ENV, keys.privateKey);
28993
+ }
28994
+ source = "dev";
28995
+ }
28996
+ const invalid = validateVapidKeys(keys);
28997
+ if (invalid) return {
28998
+ ok: false,
28999
+ reason: `The VAPID keys are unusable: ${invalid}. ${HOW_TO_GENERATE}`
29000
+ };
29001
+ const subject = input.vapid?.subject?.trim() || env["REBASE_VAPID_SUBJECT"]?.trim() || publicUrlSubject(env.REBASE_PUBLIC_URL) || (isProduction ? void 0 : "mailto:push@localhost.invalid");
29002
+ if (!subject) return {
29003
+ ok: false,
29004
+ reason: `Push needs a contact for the push services: set ${VAPID_SUBJECT_ENV} to a mailto: address or an https:// URL.`
29005
+ };
29006
+ if (!/^(mailto:.+|https:\/\/.+)$/.test(subject)) return {
29007
+ ok: false,
29008
+ reason: `${VAPID_SUBJECT_ENV} must be a mailto: address or an https:// URL; got ${JSON.stringify(subject)}.`
29009
+ };
29010
+ return {
29011
+ ok: true,
29012
+ keys,
29013
+ subject,
29014
+ source
29015
+ };
29016
+ }
29017
+ function publicUrlSubject(publicUrl) {
29018
+ if (!publicUrl) return void 0;
29019
+ try {
29020
+ const url = new URL(publicUrl);
29021
+ return url.protocol === "https:" ? url.origin : void 0;
29022
+ } catch {
29023
+ return;
29024
+ }
29025
+ }
29026
+ //#endregion
29027
+ //#region src/push/web-push-sender.ts
29028
+ /** How long one push service gets to answer. */
29029
+ var SEND_TIMEOUT_MS = 15e3;
29030
+ /**
29031
+ * The default {@link PushSender}: signs with this backend's VAPID keys,
29032
+ * encrypts to the browser's key and posts the message with `fetch`.
29033
+ *
29034
+ * Redirects are not followed. A push service answers a message itself, and
29035
+ * following a `Location` would let an allowed host send this server anywhere.
29036
+ */
29037
+ function createWebPushSender(keys, subject) {
29038
+ return { async send(target, payload, options) {
29039
+ const body = encryptPayload(Buffer.from(payload, "utf8"), target.p256dh, target.auth);
29040
+ const headers = {
29041
+ "Content-Type": "application/octet-stream",
29042
+ "Content-Encoding": "aes128gcm",
29043
+ TTL: String(options.ttl),
29044
+ Urgency: options.urgency,
29045
+ Authorization: vapidAuthorization(target.endpoint, keys, subject)
29046
+ };
29047
+ if (options.topic) headers.Topic = options.topic;
29048
+ const response = await fetch(target.endpoint, {
29049
+ method: "POST",
29050
+ headers,
29051
+ body: new Uint8Array(body),
29052
+ redirect: "manual",
29053
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
29054
+ });
29055
+ const text = await response.text().catch(() => "");
29056
+ return {
29057
+ statusCode: response.status,
29058
+ body: text ? text.slice(0, 500) : void 0
29059
+ };
29060
+ } };
29061
+ }
29062
+ //#endregion
29063
+ //#region src/push/set-up.ts
29064
+ var OFF_REASON = "Push notifications are off on this backend. Set `push: true` in the backend options to turn them on.";
29065
+ /**
29066
+ * Turn `push` in the backend options into `rebase.push`: resolve the keys,
29067
+ * create (or, without provisioning, check) the table, and build the service.
29068
+ * Never throws: a backend that cannot push still serves everything else, and
29069
+ * the reason is logged once and carried by every refusal.
29070
+ */
29071
+ async function setUpPush(input) {
29072
+ if (!input.push) return {
29073
+ enabled: false,
29074
+ service: createUnconfiguredPushService(OFF_REASON),
29075
+ allowedHosts: []
29076
+ };
29077
+ const options = input.push === true ? {} : input.push;
29078
+ const allowedHosts = options.allowedHosts ?? [];
29079
+ const env = input.env ?? process.env;
29080
+ const isProduction = env.NODE_ENV === "production";
29081
+ const unconfigured = (reason) => {
29082
+ logger.warn(`[push] ${reason}`);
29083
+ return {
29084
+ enabled: true,
29085
+ service: createUnconfiguredPushService(reason),
29086
+ reason,
29087
+ allowedHosts
29088
+ };
29089
+ };
29090
+ const admin = input.driver.admin;
29091
+ if (!isSQLAdmin(admin)) return unconfigured("Push needs a SQL database for its subscriptions; this backend's database driver has none.");
29092
+ const vapid = resolveVapid({
29093
+ vapid: options.vapid,
29094
+ env,
29095
+ isProduction,
29096
+ devStore: shouldCacheDevSecrets(env) ? openDevSecretStore() : void 0
29097
+ });
29098
+ if (!vapid.ok) return unconfigured(vapid.reason);
29099
+ if (vapid.source === "dev") logger.info(`[push] No VAPID keys set, so this development server uses generated ones (kept in .rebase-dev-secrets.json). For production set ${VAPID_PUBLIC_ENV} and ${VAPID_PRIVATE_ENV}: \`npx web-push generate-vapid-keys\`.`);
29100
+ const store = createPushStore((sql, params) => admin.executeSql(sql, params ? { params } : void 0));
29101
+ try {
29102
+ if (input.provision) await store.ensure();
29103
+ else await store.adopt();
29104
+ } catch (error) {
29105
+ logger.error("[push] could not prepare rebase.push_subscriptions", { error });
29106
+ return unconfigured(`Push could not prepare its subscription table: ${error instanceof Error ? error.message : String(error)}`);
29107
+ }
29108
+ return {
29109
+ enabled: true,
29110
+ service: createPushService({
29111
+ store,
29112
+ sender: options.sender ?? createWebPushSender(vapid.keys, vapid.subject),
29113
+ publicKey: vapid.keys.publicKey
29114
+ }),
29115
+ store,
29116
+ allowedHosts
29117
+ };
29118
+ }
29119
+ //#endregion
29120
+ //#region src/push/push-routes.ts
29121
+ /**
29122
+ * The browser's side of push, normally under `/api/push`:
29123
+ *
29124
+ * GET /key the VAPID public key a browser subscribes with -> { key }
29125
+ * POST /subscriptions { subscription, lang? } this browser takes notifications, for the caller -> { id }
29126
+ * DELETE /subscriptions { endpoint } it does not any more -> { removed }
29127
+ *
29128
+ * Every route needs a signed-in person. An API key or the service key is
29129
+ * refused: a subscription is a browser belonging to an account, and a script
29130
+ * has neither.
29131
+ */
29132
+ function callerUid(c) {
29133
+ if (c.get("apiKey")) throw ApiError.forbidden("Push subscriptions belong to a signed-in person, not an API key.", "PUSH_NEEDS_A_USER");
29134
+ const user = c.get("user");
29135
+ const uid = user && typeof user === "object" && "uid" in user && typeof user.uid === "string" ? user.uid : void 0;
29136
+ if (!uid) throw ApiError.unauthenticated("Authentication required");
29137
+ if (uid === "service") throw ApiError.forbidden("Push subscriptions belong to a signed-in person, not the service key.", "PUSH_NEEDS_A_USER");
29138
+ return uid;
29139
+ }
29140
+ async function readObject(c) {
29141
+ let body;
29142
+ try {
29143
+ body = await c.req.json();
29144
+ } catch {
29145
+ throw ApiError.badRequest("Request body must be JSON", "INVALID_INPUT");
29146
+ }
29147
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw ApiError.badRequest("Request body must be a JSON object", "INVALID_INPUT");
29148
+ return Object.fromEntries(Object.entries(body));
29149
+ }
29150
+ function field(value, key) {
29151
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? Reflect.get(value, key) : void 0;
29152
+ }
29153
+ function createPushRoutes(options) {
29154
+ const { service, store, auth, allowedHosts = [] } = options;
29155
+ const router = new Hono();
29156
+ router.onError(errorHandler);
29157
+ router.use("/*", auth);
29158
+ for (const middleware of options.after ?? []) router.use("/*", middleware);
29159
+ const configuredStore = () => {
29160
+ if (!store || !service.isConfigured()) throw ApiError.serviceUnavailable(options.unconfiguredReason ?? "Push notifications are not configured on this server.", "PUSH_NOT_CONFIGURED");
29161
+ return store;
29162
+ };
29163
+ router.get("/key", (c) => {
29164
+ callerUid(c);
29165
+ configuredStore();
29166
+ c.header("Cache-Control", "no-store");
29167
+ return c.json({ key: service.publicKey() });
29168
+ });
29169
+ router.post("/subscriptions", async (c) => {
29170
+ const userId = callerUid(c);
29171
+ const target = configuredStore();
29172
+ const body = await readObject(c);
29173
+ const subscription = body.subscription;
29174
+ const endpoint = acceptEndpoint(field(subscription, "endpoint"), allowedHosts);
29175
+ if (!endpoint) throw ApiError.badRequest("subscription.endpoint is not on a known push service.", "PUSH_ENDPOINT_REFUSED");
29176
+ const keys = field(subscription, "keys");
29177
+ const p256dh = acceptP256dh(field(keys, "p256dh"));
29178
+ const authSecret = acceptAuthSecret(field(keys, "auth"));
29179
+ if (!p256dh || !authSecret) throw ApiError.badRequest("subscription.keys must carry the browser's p256dh and auth, as PushSubscription.toJSON() gives them.", "INVALID_INPUT");
29180
+ const id = subscriptionIdOf(endpoint);
29181
+ await target.upsert({
29182
+ id,
29183
+ userId,
29184
+ endpoint,
29185
+ p256dh,
29186
+ auth: authSecret,
29187
+ lang: acceptLang(body.lang),
29188
+ userAgent: c.req.header("user-agent")?.slice(0, 300) ?? null
29189
+ });
29190
+ return c.json({ id });
29191
+ });
29192
+ router.delete("/subscriptions", async (c) => {
29193
+ const userId = callerUid(c);
29194
+ const target = configuredStore();
29195
+ const endpoint = acceptEndpoint((await readObject(c)).endpoint, allowedHosts);
29196
+ const removed = endpoint ? await target.removeOwn(subscriptionIdOf(endpoint), userId) : false;
29197
+ return c.json({ removed });
29198
+ });
29199
+ return router;
29200
+ }
29201
+ //#endregion
28203
29202
  //#region src/singleton.ts
28204
29203
  /**
28205
29204
  * The backing instance lives on a process-global slot, NOT in a module-local
@@ -28851,7 +29850,7 @@ async function buildRebaseBackend(options, announcements) {
28851
29850
  const platformTokenPreAuth = createPlatformTokenPreAuth(platformTokens);
28852
29851
  let backupLinkRouter;
28853
29852
  if (surfaces.admin) {
28854
- const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-B-1oW6qX.js").then((n) => n.t);
29853
+ const { createBackupLinkRoutes, backupDestinationFromEnv } = await import("./backup-g2ohsDe0.js").then((n) => n.t);
28855
29854
  backupLinkRouter = createBackupLinkRoutes({ getDestination: () => backupDestinationFromEnv(process.env) });
28856
29855
  }
28857
29856
  const apiKeyRouter = apiKeyStore && surfaces.admin ? createApiKeyRoutes({
@@ -28892,6 +29891,7 @@ async function buildRebaseBackend(options, announcements) {
28892
29891
  access,
28893
29892
  authLimiters,
28894
29893
  rateLimitStore: sharedRateLimitStore,
29894
+ clientAddress: requestClientAddress,
28895
29895
  apiKeyStore,
28896
29896
  tables: () => tableRegistry.list()
28897
29897
  };
@@ -29025,7 +30025,7 @@ async function buildRebaseBackend(options, announcements) {
29025
30025
  ]) {
29026
30026
  const providerConfig = safeAuthConfig[key];
29027
30027
  if (providerConfig && requiredFields.every((f) => Boolean(providerConfig[f]))) {
29028
- const createFn = (await import("./auth-BOz84vIr.js").then((n) => n.t))[factory];
30028
+ const createFn = (await import("./auth-Bfwjg4Bg.js").then((n) => n.t))[factory];
29029
30029
  oauthProviders.push(createFn(providerConfig));
29030
30030
  }
29031
30031
  }
@@ -29292,11 +30292,11 @@ async function buildRebaseBackend(options, announcements) {
29292
30292
  let schemaEditorOff = schemaEditorUnavailable();
29293
30293
  let schemaEditorRoutes;
29294
30294
  let tableSourceEditor;
29295
- const loadTableSourceEditor = (dir) => tableSourceEditor ??= import("./schema-editor-routes-CzITcAgt.js").then((module) => module.createTableSourceEditor(dir));
30295
+ const loadTableSourceEditor = (dir) => tableSourceEditor ??= import("./schema-editor-routes-DEGwyQmx.js").then((module) => module.createTableSourceEditor(dir));
29296
30296
  const tsMorphMissing = (err) => typeof err === "object" && err !== null && "code" in err && err.code === "ERR_MODULE_NOT_FOUND";
29297
30297
  if (!schemaEditorOff && config.schemaDir) try {
29298
30298
  const editor = await loadTableSourceEditor(config.schemaDir);
29299
- schemaEditorRoutes = (await import("./schema-editor-routes-CzITcAgt.js")).createSchemaEditorRoutes(editor, { getAdmin: () => defaultDriver.admin });
30299
+ schemaEditorRoutes = (await import("./schema-editor-routes-DEGwyQmx.js")).createSchemaEditorRoutes(editor, { getAdmin: () => defaultDriver.admin });
29300
30300
  } catch (err) {
29301
30301
  if (tsMorphMissing(err)) {
29302
30302
  schemaEditorOff = {
@@ -29351,7 +30351,7 @@ async function buildRebaseBackend(options, announcements) {
29351
30351
  let remoteEditingOff;
29352
30352
  if (remoteRepo) {
29353
30353
  try {
29354
- remoteEditor = await import("./table-source-editor-qmyi5vxX.js").then((n) => n.u);
30354
+ remoteEditor = await import("./table-source-editor-D_zNDhEU.js").then((n) => n.u);
29355
30355
  } catch (err) {
29356
30356
  if (err?.code !== "ERR_MODULE_NOT_FOUND") throw err;
29357
30357
  remoteEditingOff = {
@@ -29798,6 +30798,31 @@ async function buildRebaseBackend(options, announcements) {
29798
30798
  Object.assign(serverClient, { email: attached });
29799
30799
  logger.debug("Email service attached to singleton", { configured: attached.isConfigured() });
29800
30800
  }
30801
+ const pushSetUp = await setUpPush({
30802
+ push: config.push,
30803
+ driver: defaultDriver,
30804
+ provision: provision.database
30805
+ });
30806
+ Object.assign(serverClient, { push: pushSetUp.service });
30807
+ let pushSurface;
30808
+ if (pushSetUp.enabled) pushSurface = createPushRoutes({
30809
+ service: pushSetUp.service,
30810
+ store: pushSetUp.store,
30811
+ unconfiguredReason: pushSetUp.reason,
30812
+ allowedHosts: pushSetUp.allowedHosts,
30813
+ auth: authAdapter ? createAdapterAuthMiddleware({
30814
+ adapter: authAdapter,
30815
+ driver: defaultDriver,
30816
+ requireAuth: true,
30817
+ apiKeyStore
30818
+ }) : createAuthMiddleware({
30819
+ driver: defaultDriver,
30820
+ requireAuth: true,
30821
+ serviceKey: internalServiceKey,
30822
+ apiKeyStore
30823
+ }),
30824
+ after: rateLimitConfig ? [createDataRateLimiter(rateLimitConfig)] : []
30825
+ });
29801
30826
  const driverAdmin = defaultBootstrapper.getAdmin?.(defaultDriverResult);
29802
30827
  if (isSQLAdmin(driverAdmin)) {
29803
30828
  const sqlAdminFor = (key) => {
@@ -29832,9 +30857,9 @@ async function buildRebaseBackend(options, announcements) {
29832
30857
  /** Function and cron files that failed to import, for `requireFilesLoaded`. */
29833
30858
  const loadFailures = [];
29834
30859
  if ((config.functionsDir || config.functions) && surfaces.functions) {
29835
- const { functionList, readFunctionsDirectory } = await import("./function-loader-BeFbN1-A.js").then((n) => n.t);
29836
- const { createFunctionRoutes } = await import("./function-routes-CIwLXsZF.js").then((n) => n.n);
29837
- const { createFunctionsRequestTimeout, resolveFunctionsTimeoutMs } = await import("./request-timeout-CpOgfQPK.js").then((n) => n.t);
30860
+ const { functionList, readFunctionsDirectory } = await import("./function-loader-D3YEHF6E.js").then((n) => n.t);
30861
+ const { createFunctionRoutes } = await import("./function-routes-DNDFIa7t.js").then((n) => n.n);
30862
+ const { createFunctionsRequestTimeout, resolveFunctionsTimeoutMs } = await import("./request-timeout-cC3HT1Pf.js").then((n) => n.t);
29838
30863
  const { functions: functionRecord, problems, failed } = config.functions ? {
29839
30864
  functions: config.functions,
29840
30865
  problems: [],
@@ -29842,7 +30867,7 @@ async function buildRebaseBackend(options, announcements) {
29842
30867
  } : await readFunctionsDirectory(config.functionsDir);
29843
30868
  loadFailures.push(...failed);
29844
30869
  const allFunctions = functionList(functionRecord);
29845
- const { selectFunctions } = await import("./selection-hgC1szl6.js").then((n) => n.n);
30870
+ const { selectFunctions } = await import("./selection-BOnbJvXD.js").then((n) => n.n);
29846
30871
  const loadedFunctions = selectFunctions(allFunctions, config.functionsSelection);
29847
30872
  servedFunctionNames = loadedFunctions.map((fn) => fn.name);
29848
30873
  if (loadedFunctions.length !== allFunctions.length) logger.info("Serving a subset of this bundle's functions", {
@@ -29891,7 +30916,7 @@ async function buildRebaseBackend(options, announcements) {
29891
30916
  }
29892
30917
  const forwardsFunctionsOnlyInProcess = !surfaces.functions && !surfaces.auth && !surfaces.data && !surfaces.storage && !surfaces.admin && !surfaces.meta;
29893
30918
  if (config.functionsUpstream && !surfaces.functions) {
29894
- const { createFunctionsProxy } = await import("./proxy-D18_bcQI.js").then((n) => n.t);
30919
+ const { createFunctionsProxy } = await import("./proxy-clweqa43.js").then((n) => n.t);
29895
30920
  functionsSurface = createFunctionsProxy({ upstream: config.functionsUpstream });
29896
30921
  logger.info(forwardsFunctionsOnlyInProcess ? "Forwarding this process's own function calls (rebase.functions) to another process" : "Forwarding custom functions to another process", { upstream: config.functionsUpstream });
29897
30922
  }
@@ -29900,10 +30925,10 @@ async function buildRebaseBackend(options, announcements) {
29900
30925
  /** How many cron jobs `start()` schedules in this process. */
29901
30926
  let cronJobsToSchedule = 0;
29902
30927
  if (surfaces.cron || (config.cronsDir || config.crons || storageSweepJobs.length > 0) && ownership.cronScheduler) {
29903
- const { cronJobsFrom, readCronsDirectory, withHiddenPropertiesOf } = await import("./cron-loader-BDN8plQK.js").then((n) => n.t);
29904
- const { CronScheduler } = await import("./cron-scheduler-DgrsqyQQ.js").then((n) => n.n);
29905
- const { createCronRoutes } = await import("./cron-routes-BOu-bY7I.js").then((n) => n.n);
29906
- const { createCronStore } = await import("./cron-store-91cd9Qzv.js").then((n) => n.n);
30928
+ const { cronJobsFrom, readCronsDirectory, withHiddenPropertiesOf } = await import("./cron-loader-BBP0kBIl.js").then((n) => n.t);
30929
+ const { CronScheduler } = await import("./cron-scheduler-CopTWKYB.js").then((n) => n.n);
30930
+ const { createCronRoutes } = await import("./cron-routes-Du03uJ7K.js").then((n) => n.n);
30931
+ const { createCronStore } = await import("./cron-store-FGaZOdMf.js").then((n) => n.n);
29907
30932
  const { crons: cronRecord, problems: cronProblems, failed: cronFailures } = config.crons ? {
29908
30933
  crons: config.crons,
29909
30934
  problems: [],
@@ -29968,7 +30993,7 @@ async function buildRebaseBackend(options, announcements) {
29968
30993
  }
29969
30994
  let metricsHistory;
29970
30995
  try {
29971
- const { createMetricsHistory } = await import("./history-recorder-CNeqtTaR.js");
30996
+ const { createMetricsHistory } = await import("./history-recorder-C5RkbKS2.js");
29972
30997
  metricsHistory = createMetricsHistory(defaultDriver, { provision: provision.database });
29973
30998
  if (metricsHistory) await metricsHistory.ensure();
29974
30999
  } catch (err) {
@@ -29977,7 +31002,7 @@ async function buildRebaseBackend(options, announcements) {
29977
31002
  }
29978
31003
  let jobQueue;
29979
31004
  if (jobsOptions?.enabled) {
29980
- const { createJobStore, createJobQueue } = await import("./jobs-WCyKVsUf.js").then((n) => n.t);
31005
+ const { createJobStore, createJobQueue } = await import("./jobs-CFUwQTao.js").then((n) => n.t);
29981
31006
  const store = createJobStore(defaultDriver, { provision: provision.database });
29982
31007
  if (store) {
29983
31008
  await store.ensureTable();
@@ -30025,7 +31050,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30025
31050
  /** Who `/api/docs` is served to by default: the schema endpoint's callers (see `init/docs`). */
30026
31051
  let docsAudience;
30027
31052
  if (surfaces.admin) {
30028
- const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-B-1oW6qX.js").then((n) => n.t);
31053
+ const { createBackupRoutes, backupDestinationFromEnv, readBackupSchedule } = await import("./backup-g2ohsDe0.js").then((n) => n.t);
30029
31054
  const backupRouter = new Hono();
30030
31055
  applyAdminGate(backupRouter, "Backup", "backups:read");
30031
31056
  const scheduler = cronScheduler;
@@ -30047,7 +31072,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30047
31072
  }
30048
31073
  let rlsSimulatorSurface;
30049
31074
  if (surfaces.admin) {
30050
- const { createRlsSimulatorRoutes } = await import("./rls-simulator-routes-BvH6wI64.js");
31075
+ const { createRlsSimulatorRoutes } = await import("./rls-simulator-routes-DI2sYaQt.js");
30051
31076
  const rlsSimulatorRouter = new Hono();
30052
31077
  applyAdminGate(rlsSimulatorRouter, "RLS simulator", "schema:read");
30053
31078
  rlsSimulatorRouter.route("/", createRlsSimulatorRoutes({
@@ -30059,14 +31084,14 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30059
31084
  rlsSimulatorSurface = rlsSimulatorRouter;
30060
31085
  }
30061
31086
  if (surfaces.admin) {
30062
- const { createSqlExportRoutes } = await import("./sql-export-routes-BKmQZ3xh.js");
31087
+ const { createSqlExportRoutes } = await import("./sql-export-routes-B3oqb1Jw.js");
30063
31088
  const sqlExportRouter = new Hono();
30064
31089
  applyAdminGate(sqlExportRouter, "SQL export", "database:write");
30065
31090
  sqlExportRouter.route("/", createSqlExportRoutes({ getAdmin: () => defaultDriver.admin }));
30066
31091
  sqlExportSurface = sqlExportRouter;
30067
31092
  }
30068
31093
  if (surfaces.admin) {
30069
- const { createBranchRoutes } = await import("./branch-routes-0xhHXlGq.js");
31094
+ const { createBranchRoutes } = await import("./branch-routes-DtNtc0Vh.js");
30070
31095
  const branchRouter = new Hono();
30071
31096
  applyAdminGate(branchRouter, "Branch review", "database:write");
30072
31097
  branchRouter.route("/", createBranchRoutes({ getAdmin: () => defaultDriver.admin }));
@@ -30098,14 +31123,14 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30098
31123
  devMailSurface = devMailRouter;
30099
31124
  }
30100
31125
  if (surfaces.admin) {
30101
- const { createLogsRoutes } = await import("./logs-routes-BT4af1Or.js").then((n) => n.n);
31126
+ const { createLogsRoutes } = await import("./logs-routes-C3CLYP-n.js").then((n) => n.n);
30102
31127
  const logsRouter = new Hono();
30103
31128
  applyAdminGate(logsRouter, "Logs", "logs:read");
30104
31129
  logsRouter.route("/", createLogsRoutes({}, { closeSignal: longLivedResponses.signal }));
30105
31130
  logsSurface = logsRouter;
30106
31131
  }
30107
31132
  if (surfaces.meta) {
30108
- const { createContractRoutes } = await import("./contract-routes-o5oqNhfc.js").then((n) => n.t);
31133
+ const { createContractRoutes } = await import("./contract-routes-CZTlAP7p.js").then((n) => n.t);
30109
31134
  const contractRouter = new Hono();
30110
31135
  if (adminSurfacesGated) contractRouter.use("/contract", ...adminGate("schema:read"));
30111
31136
  else {
@@ -30115,7 +31140,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30115
31140
  } }, 404));
30116
31141
  warnOnMount("meta", "Contract endpoint disabled: no auth is configured (no adapter or no jwtSecret), and it would otherwise expose the full schema to anyone. `/api/meta/schema-version` is still served.");
30117
31142
  }
30118
- const { createSchemaTablesService, createSchemaTablesRoutes } = await import("./schema-tables-routes-Uss-ljon.js").then((n) => n.n);
31143
+ const { createSchemaTablesService, createSchemaTablesRoutes } = await import("./schema-tables-routes-BfsNG4c4.js").then((n) => n.n);
30119
31144
  const schemaTables = createSchemaTablesService({
30120
31145
  tableRegistry,
30121
31146
  policySource: () => servedPolicyTables,
@@ -30258,6 +31283,10 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30258
31283
  const schemaGroup = group(schemaTablesSurface);
30259
31284
  schemaGroup.onError(errorHandler);
30260
31285
  return schemaGroup;
31286
+ },
31287
+ push: () => {
31288
+ if (!pushSurface) throw new Error("routes.push(): this backend was created without `push`. Pass `push: true` to serve push subscriptions.");
31289
+ return group(pushSurface);
30261
31290
  }
30262
31291
  };
30263
31292
  /**
@@ -30278,7 +31307,8 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30278
31307
  admin: servedGroup("admin"),
30279
31308
  cron: servedGroup("cron"),
30280
31309
  meta: servedGroup("meta"),
30281
- schema: servedGroup("schema")
31310
+ schema: servedGroup("schema"),
31311
+ push: servedGroup("push")
30282
31312
  };
30283
31313
  /** The base path the application last mounted at — where the SDK's socket dials by default. */
30284
31314
  let mountedBasePath;
@@ -30350,6 +31380,7 @@ Use a driver that supports the job queue, or remove the declarations. Refusing t
30350
31380
  if (logsSurface) app.route(`${basePath}/logs`, deprecatedAlias(logsSurface, `${basePath}/admin/logs`));
30351
31381
  if (surfaces.meta && metaSurface) app.route(`${basePath}/meta`, groups.meta());
30352
31382
  if (surfaces.meta && schemaTablesSurface) app.route(`${basePath}/schema`, groups.schema());
31383
+ if (pushSurface && surfaces.data) app.route(`${basePath}/push`, groups.push());
30353
31384
  if (announce) logger.debug("Rebase backend mounted", { basePath });
30354
31385
  };
30355
31386
  const mountInProcessAdmin = (app, basePath) => {
@@ -30529,7 +31560,7 @@ function realtimeSocketPath(basePath) {
30529
31560
  * backend no MCP client calls never loads it.
30530
31561
  */
30531
31562
  async function loadMcpApps() {
30532
- const { MCP_APPS } = await import("./dist-fBcYxf4h.js");
31563
+ const { MCP_APPS } = await import("./dist-C1vNURUy.js");
30533
31564
  return withProjectView(MCP_APPS, [...process.env.REBASE_MCP_VIEW ? [process.env.REBASE_MCP_VIEW] : [], ...servedFrontendPaths().map((frontend) => path.join(frontend, PROJECT_VIEW_FILE))], (file) => {
30534
31565
  try {
30535
31566
  return readFileSync(file, "utf8");
@@ -30543,7 +31574,7 @@ async function loadMcpApps() {
30543
31574
  * app to the modules and names every view serves (`MCP_APP_MODULES`).
30544
31575
  */
30545
31576
  async function loadAppCompiler() {
30546
- const { compileApp } = await import("./dist-fBcYxf4h.js");
31577
+ const { compileApp } = await import("./dist-C1vNURUy.js");
30547
31578
  return (source) => compileApp(source, MCP_APP_MODULES);
30548
31579
  }
30549
31580
  /**
@@ -30886,130 +31917,6 @@ var authJwt = () => {
30886
31917
  return sql$1.raw(RLS_JWT_SQL);
30887
31918
  };
30888
31919
  //#endregion
30889
- //#region src/dev-secrets.ts
30890
- /**
30891
- * Development secrets that survive a restart.
30892
- *
30893
- * `loadEnv` generates `JWT_SECRET` and `REBASE_SERVICE_KEY` when they are unset
30894
- * outside production, so a developer can start without setting anything up. It
30895
- * generated them **freshly on every boot**, which meant every restart of the dev
30896
- * server silently invalidated the previous run's tokens: you were logged out of
30897
- * your own app because you edited a file, and the API key you had just made
30898
- * stopped working.
30899
- *
30900
- * The CLI already worked around it for scaffolded projects by writing a stable
30901
- * `JWT_SECRET` into `.env` at `rebase init` — the comment there says exactly
30902
- * why. That leaves anyone who did not scaffold, and anyone running from a
30903
- * container with no `.env`, with the logout-on-restart behaviour.
30904
- *
30905
- * So the generated values are cached in a file beside the other dev-state
30906
- * files — `.rebase-dev-port` and `.rebase-dev-url` follow the same convention
30907
- * and are gitignored in the same place.
30908
- *
30909
- * ## What this does not change
30910
- *
30911
- * Production. `loadEnv` refuses to start when a secret was auto-generated and
30912
- * `NODE_ENV=production`, and that is untouched: this only makes the
30913
- * already-generated development values stable. There is no path by which a
30914
- * cached secret becomes a production one.
30915
- *
30916
- * ## Failing soft
30917
- *
30918
- * A read-only filesystem, a container without a writable working directory, a
30919
- * permissions problem — none of these should stop a development server from
30920
- * starting. Every failure here falls back to the previous behaviour, an
30921
- * ephemeral secret, and says so once at debug level.
30922
- */
30923
- /** Beside `.rebase-dev-port` and `.rebase-dev-url`, and gitignored with them. */
30924
- var DEV_SECRETS_FILENAME = ".rebase-dev-secrets.json";
30925
- /** Owner read/write only. These are secrets, even development ones. */
30926
- var FILE_MODE = 384;
30927
- /** Whether these environment variables describe a test runner. */
30928
- function detectTestRunner(env) {
30929
- return Boolean(env.JEST_WORKER_ID || env.VITEST || env.VITEST_WORKER_ID || env.NODE_ENV === "test");
30930
- }
30931
- /**
30932
- * Whether a test runner started this process, decided **once at import**.
30933
- *
30934
- * Read at call time it would be wrong, and provably so: `env.test.ts` does
30935
- * `process.env = {}` in its `beforeEach`, which erases `NODE_ENV` and
30936
- * `JEST_WORKER_ID` alike. A predicate consulting the live environment therefore
30937
- * sees a bare object and concludes "development", which is how the first version
30938
- * of this dropped a `.rebase-dev-secrets.json` into `packages/server` on every
30939
- * test run.
30940
- *
30941
- * Whether a test runner is hosting the process is a fact about the process, not
30942
- * about whatever a test has since done to `process.env`, so it is captured
30943
- * before any test can rewrite it.
30944
- */
30945
- var TEST_RUNNER_DETECTED = detectTestRunner(process.env);
30946
- /**
30947
- * Whether generated secrets should be cached at all.
30948
- *
30949
- * Not in production — `loadEnv` refuses to boot there on a generated secret, so
30950
- * there is nothing to cache and no path by which a cached one becomes a
30951
- * production one.
30952
- *
30953
- * Not under a test runner: a test must not inherit a secret a previous run left
30954
- * behind, and a library call has no business writing into a suite's working
30955
- * directory. `inTestRunner` is a parameter only so this predicate can be tested
30956
- * on its own; callers pass nothing.
30957
- */
30958
- function shouldCacheDevSecrets(env = process.env, inTestRunner = TEST_RUNNER_DETECTED) {
30959
- if (inTestRunner) return false;
30960
- return env.NODE_ENV !== "production";
30961
- }
30962
- /** `REBASE_DEV_SECRETS_FILE`, or the conventional name in the working directory. */
30963
- function resolveDevSecretsFile(env = process.env) {
30964
- const override = env.REBASE_DEV_SECRETS_FILE?.trim();
30965
- if (override) return path$3.resolve(override);
30966
- return path$3.join(process.cwd(), DEV_SECRETS_FILENAME);
30967
- }
30968
- /**
30969
- * Open the cache.
30970
- *
30971
- * Reading a malformed file is treated as an empty cache rather than an error:
30972
- * the file is ours, it holds regenerable values, and refusing to boot over a
30973
- * corrupted convenience cache would be worse than rewriting it.
30974
- */
30975
- function openDevSecretStore(file = resolveDevSecretsFile()) {
30976
- let cache = {};
30977
- let usable = true;
30978
- try {
30979
- if (fs$3.existsSync(file)) {
30980
- const parsed = JSON.parse(fs$3.readFileSync(file, "utf-8"));
30981
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
30982
- for (const [key, value] of Object.entries(parsed)) if (typeof value === "string" && value.length > 0) cache[key] = value;
30983
- }
30984
- }
30985
- } catch {
30986
- cache = {};
30987
- }
30988
- const flush = () => {
30989
- try {
30990
- fs$3.mkdirSync(path$3.dirname(file), { recursive: true });
30991
- fs$3.writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`, { mode: FILE_MODE });
30992
- fs$3.chmodSync(file, FILE_MODE);
30993
- } catch (err) {
30994
- if (usable) {
30995
- usable = false;
30996
- logger.debug(`[dev-secrets] Could not write ${file}, so generated development secrets will not survive a restart: ${err instanceof Error ? err.message : String(err)}`);
30997
- }
30998
- }
30999
- };
31000
- return {
31001
- file,
31002
- get usable() {
31003
- return usable;
31004
- },
31005
- get: (name) => cache[name],
31006
- set: (name, value) => {
31007
- cache[name] = value;
31008
- flush();
31009
- }
31010
- };
31011
- }
31012
- //#endregion
31013
31920
  //#region src/env.ts
31014
31921
  /**
31015
31922
  * Generate a cryptographically secure random secret (hex-encoded).
@@ -32024,7 +32931,7 @@ var WebhookDispatcher = class {
32024
32931
  "X-Webhook-Attempt": String(attemptNumber),
32025
32932
  ...webhook.headers || {}
32026
32933
  };
32027
- if (webhook.secret) headers["X-Webhook-Signature"] = `sha256=${createHmac("sha256", webhook.secret).update(body).digest("hex")}`;
32934
+ if (webhook.secret) headers["X-Webhook-Signature"] = `sha256=${createHmac$1("sha256", webhook.secret).update(body).digest("hex")}`;
32028
32935
  const controller = new AbortController();
32029
32936
  const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
32030
32937
  try {
@@ -32853,6 +33760,17 @@ var bootEnvExtension = z$1.object({
32853
33760
  "false",
32854
33761
  ""
32855
33762
  ]).default("true").transform((v) => v !== "false"),
33763
+ /**
33764
+ * `true` turns on Web Push (`push: true`): the `/push` routes, the
33765
+ * `rebase.push_subscriptions` table and `rebase.push`. Off by default. The
33766
+ * keys are `REBASE_VAPID_PUBLIC_KEY`, `REBASE_VAPID_PRIVATE_KEY` and
33767
+ * `REBASE_VAPID_SUBJECT`, read where push is set up.
33768
+ */
33769
+ REBASE_PUSH: z$1.enum([
33770
+ "true",
33771
+ "false",
33772
+ ""
33773
+ ]).default("false").transform((v) => v === "true"),
32856
33774
  /** Comma-separated origins allowed to make credentialed cross-origin calls. */
32857
33775
  CORS_ORIGINS: z$1.string().optional(),
32858
33776
  /**
@@ -33431,6 +34349,108 @@ function planStaticAppMounts(apps) {
33431
34349
  owns: (request) => resolve(request) === app
33432
34350
  }));
33433
34351
  }
34352
+ /**
34353
+ * Which static app route answers a request, if any: the one rule, written once.
34354
+ *
34355
+ * A route applies only where its app is the one that answers the request — by
34356
+ * {@link createStaticAppResolver}, the rule every mount asks — so a route on
34357
+ * the site at `/` does not reach a request another app owns, on its hostname
34358
+ * or under its path. Of that app's routes the most specific wins
34359
+ * (`compareStaticRoutes`).
34360
+ *
34361
+ * Nothing under the API's base path is ever routed. The CLI keeps routes off
34362
+ * `/api`, but only the runtime knows `REBASE_BASE_PATH`, and a route over the
34363
+ * moved API would hand the function's own URL back to the route that made it.
34364
+ *
34365
+ * `undefined` when no app declares a route, so a bundle without any installs
34366
+ * nothing at all.
34367
+ */
34368
+ function createStaticRouteResolver(apps, apiBasePath) {
34369
+ if (!apps.some((app) => app.routes?.length)) return void 0;
34370
+ const owner = createStaticAppResolver(apps);
34371
+ const ordered = new Map(apps.map((app) => [app, [...app.routes ?? []].sort(compareStaticRoutes)]));
34372
+ const apiBase = (apiBasePath || "/api").replace(/\/+$/, "") || "/api";
34373
+ return (request) => {
34374
+ if (isUnderPath(request.path, apiBase)) return void 0;
34375
+ const app = owner(request);
34376
+ if (!app) return void 0;
34377
+ for (const route of ordered.get(app) ?? []) {
34378
+ const rest = matchStaticRoute(route, request.path);
34379
+ if (rest !== void 0) return {
34380
+ app,
34381
+ route,
34382
+ functionPath: `${apiBase}/functions/${route.function}${rest}`
34383
+ };
34384
+ }
34385
+ };
34386
+ }
34387
+ /**
34388
+ * The routes of each static app that sit under the API's base path, and so are
34389
+ * never served — the routes' half of {@link staticAppsShadowedByApi}.
34390
+ */
34391
+ function staticRoutesShadowedByApi(apps, apiBasePath) {
34392
+ const base = apiBasePath.replace(/\/+$/, "");
34393
+ if (base === "") return [];
34394
+ return apps.flatMap((app) => (app.routes ?? []).filter((route) => isUnderPath(route.path.endsWith("/*") ? route.path.slice(0, -2) || "/" : route.path, base)).map((route) => ({
34395
+ app,
34396
+ route
34397
+ })));
34398
+ }
34399
+ /**
34400
+ * Serve static app routes: a request a route matches is dispatched again into
34401
+ * `app` as a request for the function's own URL, and its response is the
34402
+ * answer.
34403
+ *
34404
+ * Installed first on the app, before CORS, security headers and metrics, and
34405
+ * it answers without calling `next` — so the request passes through every one
34406
+ * of them exactly once, as the function's request, and meets the functions
34407
+ * group with everything the group expects in front of it: the body limit,
34408
+ * CSRF, auth, the scope guard, the rate limit and the function timeout. A
34409
+ * forwarder to a functions process answers it as it would answer the
34410
+ * function's URL.
34411
+ *
34412
+ * The request keeps its method, headers (`Host` among them), body, query and
34413
+ * the connection it arrived on; only the path changes. The response is the
34414
+ * function's, with one header added when it has none: the owning app's
34415
+ * Content-Security-Policy, so a routed page can be framed by the origins the
34416
+ * app allows and no others.
34417
+ */
34418
+ function serveStaticAppRoutes(app, resolve) {
34419
+ const policies = /* @__PURE__ */ new Map();
34420
+ return async (c, next) => {
34421
+ const match = resolve({
34422
+ host: c.req.header("host") ?? new URL(c.req.url).host,
34423
+ path: c.req.path
34424
+ });
34425
+ if (!match) return next();
34426
+ const url = new URL(c.req.url);
34427
+ url.pathname = match.functionPath;
34428
+ const method = c.req.method;
34429
+ const raw = c.req.raw;
34430
+ const init = {
34431
+ method,
34432
+ headers: raw.headers,
34433
+ body: method === "GET" || method === "HEAD" ? void 0 : raw.body,
34434
+ duplex: "half",
34435
+ redirect: "manual",
34436
+ signal: raw.signal
34437
+ };
34438
+ const response = await app.fetch(new Request(url, init), c.env);
34439
+ if (response.headers.has("content-security-policy")) return response;
34440
+ let policy = policies.get(match.app);
34441
+ if (policy === void 0) {
34442
+ policy = staticAppCsp(match.app.frameAncestors);
34443
+ policies.set(match.app, policy);
34444
+ }
34445
+ const headers = new Headers(response.headers);
34446
+ headers.set("Content-Security-Policy", policy);
34447
+ return new Response(response.body, {
34448
+ status: response.status,
34449
+ statusText: response.statusText,
34450
+ headers
34451
+ });
34452
+ };
34453
+ }
33434
34454
  //#endregion
33435
34455
  //#region src/boot/driver.ts
33436
34456
  /**
@@ -35408,6 +36428,8 @@ async function bootFromBundle(options = {}) {
35408
36428
  }
35409
36429
  const app = new Hono();
35410
36430
  installRootErrorHandler(app);
36431
+ const staticRoutes = env.REBASE_SERVE_STATIC ? createStaticRouteResolver(bundle.staticApps, env.REBASE_BASE_PATH) : void 0;
36432
+ if (staticRoutes) app.use("/*", serveStaticAppRoutes(app, staticRoutes));
35411
36433
  app.use("/*", runtimeCors(resolveCorsOptions(env)));
35412
36434
  app.use("/*", runtimeSecureHeaders({ hstsIncludeSubDomains: env.REBASE_HSTS_INCLUDE_SUBDOMAINS }));
35413
36435
  const metrics = env.REBASE_METRICS ? createMetricsMiddleware(env.REBASE_BASE_PATH) : void 0;
@@ -35449,6 +36471,7 @@ async function bootFromBundle(options = {}) {
35449
36471
  hooks: projectExports.hooks,
35450
36472
  auth: resolveAuthOptions(env),
35451
36473
  history: env.REBASE_HISTORY,
36474
+ push: env.REBASE_PUSH,
35452
36475
  rlsAudit,
35453
36476
  enableSwagger: resolveEnableSwagger(env),
35454
36477
  compression: env.REBASE_COMPRESSION,
@@ -35510,6 +36533,7 @@ async function bootFromBundle(options = {}) {
35510
36533
  }
35511
36534
  if (env.REBASE_SERVE_STATIC) {
35512
36535
  for (const shadowed of staticAppsShadowedByApi(bundle.staticApps, env.REBASE_BASE_PATH)) logger.error(`Static app at ${shadowed.path} is under the API's base path ${env.REBASE_BASE_PATH} (REBASE_BASE_PATH), so it is never served. Move the app in rebase.json, or the API with REBASE_BASE_PATH.`);
36536
+ for (const { app: staticApp, route } of staticRoutesShadowedByApi(bundle.staticApps, env.REBASE_BASE_PATH)) logger.error(`Static app at ${staticApp.path} routes ${route.path} to the function "${route.function}", under the API's base path ${env.REBASE_BASE_PATH} (REBASE_BASE_PATH), so the route is never served. Move the route in rebase.json, or the API with REBASE_BASE_PATH.`);
35513
36537
  for (const { app: staticApp, siblingPaths, owns } of planStaticAppMounts(bundle.staticApps)) {
35514
36538
  logger.info("Serving static assets", {
35515
36539
  path: staticApp.dir,
@@ -35528,7 +36552,8 @@ async function bootFromBundle(options = {}) {
35528
36552
  ...siblingPaths
35529
36553
  ],
35530
36554
  owns,
35531
- spa: staticApp.spa
36555
+ spa: staticApp.spa,
36556
+ frameAncestors: staticApp.frameAncestors
35532
36557
  });
35533
36558
  }
35534
36559
  }
@@ -35628,6 +36653,8 @@ function readHstsIncludeSubDomains() {
35628
36653
  }
35629
36654
  async function bootStaticApp(bundle, devRoot, options) {
35630
36655
  if (bundle.staticApps.length === 0) throw new BundleError("A static bundle declares no assets to serve.", "Its manifest has `kind: \"static\"` but no `entry.static` — rebuild the app with `rebase build`.");
36656
+ const routed = bundle.staticApps.find((staticApp) => staticApp.routes?.length);
36657
+ if (routed) throw new BundleError(`The static app at ${routed.path} routes ${routed.routes?.map((route) => route.path).join(", ")} to custom functions, and a static bundle has no functions to serve them.`, "Boot the project's backend bundle instead: `rebase build` folds every static app into it, and that process serves the app, its routes and the functions together.");
35631
36658
  const isProduction = process.env.NODE_ENV === "production";
35632
36659
  const requestedPort = readStaticPort();
35633
36660
  const basePath = process.env.REBASE_BASE_PATH || "/api";
@@ -35663,7 +36690,8 @@ async function bootStaticApp(bundle, devRoot, options) {
35663
36690
  ...siblingPaths
35664
36691
  ],
35665
36692
  owns,
35666
- spa: staticApp.spa
36693
+ spa: staticApp.spa,
36694
+ frameAncestors: staticApp.frameAncestors
35667
36695
  });
35668
36696
  }
35669
36697
  let port = requestedPort;
@@ -35890,6 +36918,6 @@ function warnOnUnusableBundleShape(bundle) {
35890
36918
  logger.warn(`This bundle declares tables at "${bundle.manifest.entry.tables}", but that directory did not resolve, so no tables were loaded and none will be created. Rebuild with \`rebase build\`.`);
35891
36919
  }
35892
36920
  //#endregion
35893
- export { ACCOUNT_SCOPED_STORAGE_BASES, ApiError, BATCH_REF_KEY, BlockedUrlError, BundleError, CONCURRENT_DDL_SQLSTATES, CORS_EXPOSED_HEADERS, CronScheduler, DATABASE_UNAVAILABLE_MESSAGE, DATA_SCOPE_VOCABULARY, DEFAULT_DRIVER_ID, DEFAULT_MAX_FILE_SIZE, DEFAULT_REFERRER_POLICY, DEFAULT_STORAGE_ID, DOCUMENT_MIME_TYPES, DefaultDriverRegistry, DefaultStorageRegistry, ETAG_HEADER, FIELD_OPERATORS, GCSStorageController, IF_MATCH_HEADER, IMAGE_MIME_TYPES, LocalStorageController, MCP_APP_URI, MCP_VIEW_TOOLS, McpToolError, MetricsRegistry, ObjectTooLargeError, PermanentJobError, RUNTIME_BUNDLE_MOUNT, RUNTIME_DEFAULT_MAX_BODY_SIZE, RUNTIME_HEALTH_PATH, RUNTIME_LIVENESS_PATH, RUNTIME_MIN_TERMINATION_GRACE_SECONDS, RUNTIME_PRESTOP_DRAIN_SECONDS, RUNTIME_PROBE_PATHS, RUNTIME_STARTUP_BUDGET_SECONDS, RawHtml, S3StorageController, SHOW_APP_CODE_GUIDE, SHOW_APP_ESSENTIALS, SHOW_APP_GUIDE_TOOL, SMTPEmailService, SchemaLoadError, StoragePolicyError, TOPOLOGY_ENV_VARS, TableRegistry, TransformCache, TusHandler, UPLOAD_COLUMN_FIELD, UPLOAD_TABLE_FIELD, UnknownStorageSourceError, WEBHOOK_DELIVERY_TASK, WebhookDispatcher, _resetRebaseMock, _setRebaseMock, accessModelFromAuthTable, activeDevEmailSink, assertAllowedOutboundUrl, assertDistinctSuffixes, assertEmailLinkBases, assertEveryKindBindable, assertFieldOpsValid, assertIfMatch, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertQueryFieldsReadable, assertUploadWithinColumnLimits, assertUploadWithinPathLimits, assertUserCreationBodyValid, assertWriteRequestValid, authJwt, authRoles, authUid, backupStorageFromEnv, blockedAddressReason, bootFromBundle, callerScopes, classifySurface, cleanupDevPortFile, clearActiveDevEmailSink, col, compileLoadedSchema, compileSchemaDefs, compileStoragePolicies, configureAccess, configureJwt, createAppleProvider, createBackupLinkRoutes, createBackupRoutes, createBitbucketProvider, createBuiltinAuthAdapter, createCallContext, createContractRoutes, createCronRoutes, createCronStore, createCustomAuthAdapter, createDdlBootstrapper, createDevEmailSink, createDiscordProvider, createEmailService, createFacebookProvider, createFunctionRoutes, createGitHubProvider, createGitLabProvider, createGoogleProvider, createHistoryRoutes, createJobQueue, createJobStore, createJwksRoutes, createJwtService, createLinkedinProvider, createMetricsMiddleware, createMetricsRoutes, createMicrosoftProvider, createRebaseBackend, createRlsAudit, createSlackProvider, createSourceBundle, createSpotifyProvider, createStorageController, createStorageRoutes, createTwitterProvider, createUnconfiguredEmailService, createUploadConstraintResolver, createUploadPathResolver, createUserThroughAuthTable, decideImpersonation, declareCrons, declaredErrorAnswer, declaredUniqueTargets, defaultBackoff, defineAuthTable, defineCron, defineFunction, defineTable, defineView, describeMismatch, devEmailSinkFor, drainBackgroundWork, envSuffixForKey, errorHandler, escapeHtml, extractLinks, extractUserFromToken, fileTokenAuth, generateSecurePassword, getAccessModel, getApiKey, getDriver, getEmailChangeNoticeTemplate, getEmailChangeTemplate, getEmailOtpTemplate, getEmailVerificationTemplate, getEnv, getJwks, getMagicLinkTemplate, getPasswordResetTemplate, getRequestId, getRoles, getSql, getUser, getUserId, getUserInvitationTemplate, getUserProfile, getWelcomeEmailTemplate, hasAsymmetricSigningKey, hasFieldOps, hasRole, hasScope, hashPassword, html, httpMethodToOperation, identityResolved, implicitDeclaration, initializeDataSource, initializeDataSources, initializeRebaseBackend, installShutdownHandlers, installUnhandledRejectionHandler, isAcceptedFile, isAdmin, isApiKeyToken, isAuthAdapter, isAuthTable, isAuthTableDef, isAuthenticated, isConcurrentDdlRace, isDataException, isDatabaseAdapter, isDatabaseUnreachable, isDuplicateObjectRace, isLocalhostOrigin, isNodeRuntime, isSchemaLoadError, isTableDef, isTopologyEnvVar, isTransformableImage, isUncountedPath, isViewDef, json, lazyResource, listBackupObjects, listenWithPortRetry, loadBackendSchema, loadBootEnv, loadBundle, loadBundleProjectExports, loadBundleSchema, loadCronJobsFromDirectory, loadCronJobsWithDiagnostics, loadCrons, loadEnv, loadFunctions, loadFunctionsFromDirectory, loadFunctionsWithDiagnostics, logger, looksLikeFieldOp, mcpAppBaseUri, mcpViewToolInputSchema, oauthCodeFlowSchema, optionalAuth, overridableSecurityHeaders, parseBackupDestination, parseBackupTimestamp, parseFieldOp, parseTransformOptions, pendingBackgroundWork, pgEnum, pkceTokenParams, policy, providerVerifiedEmail, queryTokenAuth, raw, rawQueryLoggingEnabled, readBackupBytes, readBundleManifest, readUploadColumnContext, realtimeSocketPath, rebase, refuseUnhonouredImpersonation, registerDevEmailSink, registerResourceResolver, rel, reportSimulatedContext, requireAdmin, requireAuth, requireDriver, requireEnv, requireRole, requireScope, resolveApiKey, resolveAuthHooks, resolveAuthOptions, resolveBatchRefs, resolveConflictTarget, resolveCorsOrigin, resolveDataSources, resolveDeclaredTables, resolveEmailBranding, resolveEmailLinkBase, resolveEmailOptions, resolveModulePath, resolveRequireAuth, resolveStorageAccessControl, resolveStorageBackend, resolveStorageSources, resourceResolver, resourceResolvers, rowETag, runFromBundle, runtimeKey, safeCompare, schemaDriftRemedy, serveSPA, setDefaultBackend, setLogOutput, showAppArtifactGuide, splitFieldOps, sql, summarize as summarizeRlsScan, transformImage, tryVerifyOidcIdToken, unbindableKinds, validateApiKey, validateCronExpression, validatePasswordStrength, verifyCredential, verifyOidcIdToken, verifyPassword, versionColumn, versionedMcpAppUri, waitUntil, z };
36921
+ export { ACCOUNT_SCOPED_STORAGE_BASES, ApiError, BATCH_REF_KEY, BlockedUrlError, BundleError, CONCURRENT_DDL_SQLSTATES, CORS_EXPOSED_HEADERS, CronScheduler, DATABASE_UNAVAILABLE_MESSAGE, DATA_SCOPE_VOCABULARY, DEFAULT_DRIVER_ID, DEFAULT_MAX_FILE_SIZE, DEFAULT_REFERRER_POLICY, DEFAULT_STORAGE_ID, DOCUMENT_MIME_TYPES, DefaultDriverRegistry, DefaultStorageRegistry, ETAG_HEADER, FIELD_OPERATORS, GCSStorageController, IF_MATCH_HEADER, IMAGE_MIME_TYPES, LocalStorageController, MCP_APP_URI, MCP_VIEW_TOOLS, McpToolError, MetricsRegistry, ObjectTooLargeError, PermanentJobError, RUNTIME_BUNDLE_MOUNT, RUNTIME_DEFAULT_MAX_BODY_SIZE, RUNTIME_HEALTH_PATH, RUNTIME_LIVENESS_PATH, RUNTIME_MIN_TERMINATION_GRACE_SECONDS, RUNTIME_PRESTOP_DRAIN_SECONDS, RUNTIME_PROBE_PATHS, RUNTIME_STARTUP_BUDGET_SECONDS, RawHtml, S3StorageController, SHOW_APP_CODE_GUIDE, SHOW_APP_ESSENTIALS, SHOW_APP_GUIDE_TOOL, SMTPEmailService, SchemaLoadError, StoragePolicyError, TOPOLOGY_ENV_VARS, TableRegistry, TransformCache, TusHandler, UPLOAD_COLUMN_FIELD, UPLOAD_TABLE_FIELD, UnknownStorageSourceError, WEBHOOK_DELIVERY_TASK, WebhookDispatcher, _resetRebaseMock, _setRebaseMock, accessModelFromAuthTable, activeDevEmailSink, assertAllowedOutboundUrl, assertDistinctSuffixes, assertEmailLinkBases, assertEveryKindBindable, assertFieldOpsValid, assertIfMatch, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertQueryFieldsReadable, assertUploadWithinColumnLimits, assertUploadWithinPathLimits, assertUserCreationBodyValid, assertWriteRequestValid, authJwt, authRoles, authUid, backupStorageFromEnv, blockedAddressReason, bootFromBundle, callerScopes, classifySurface, cleanupDevPortFile, clearActiveDevEmailSink, col, compileLoadedSchema, compileSchemaDefs, compileStoragePolicies, configureAccess, configureJwt, createAppleProvider, createBackupLinkRoutes, createBackupRoutes, createBitbucketProvider, createBuiltinAuthAdapter, createCallContext, createContractRoutes, createCronRoutes, createCronStore, createCustomAuthAdapter, createDdlBootstrapper, createDevEmailSink, createDiscordProvider, createEmailService, createFacebookProvider, createFunctionRoutes, createGitHubProvider, createGitLabProvider, createGoogleProvider, createHistoryRoutes, createJobQueue, createJobStore, createJwksRoutes, createJwtService, createLinkedinProvider, createMetricsMiddleware, createMetricsRoutes, createMicrosoftProvider, createRebaseBackend, createRlsAudit, createSlackProvider, createSourceBundle, createSpotifyProvider, createStorageController, createStorageRoutes, createTwitterProvider, createUnconfiguredEmailService, createUploadConstraintResolver, createUploadPathResolver, createUserThroughAuthTable, createWebPushSender, decideImpersonation, declareCrons, declaredErrorAnswer, declaredUniqueTargets, defaultBackoff, defineAuthTable, defineCron, defineFunction, defineTable, defineView, describeMismatch, devEmailSinkFor, drainBackgroundWork, envSuffixForKey, errorHandler, escapeHtml, extractLinks, extractUserFromToken, fileTokenAuth, generateSecurePassword, generateVapidKeys, getAccessModel, getApiKey, getDriver, getEmailChangeNoticeTemplate, getEmailChangeTemplate, getEmailOtpTemplate, getEmailVerificationTemplate, getEnv, getJwks, getMagicLinkTemplate, getPasswordResetTemplate, getRequestId, getRoles, getSql, getUser, getUserId, getUserInvitationTemplate, getUserProfile, getWelcomeEmailTemplate, hasAsymmetricSigningKey, hasFieldOps, hasRole, hasScope, hashPassword, html, httpMethodToOperation, identityResolved, implicitDeclaration, initializeDataSource, initializeDataSources, initializeRebaseBackend, installShutdownHandlers, installUnhandledRejectionHandler, isAcceptedFile, isAdmin, isApiKeyToken, isAuthAdapter, isAuthTable, isAuthTableDef, isAuthenticated, isConcurrentDdlRace, isDataException, isDatabaseAdapter, isDatabaseUnreachable, isDuplicateObjectRace, isLocalhostOrigin, isNodeRuntime, isSchemaLoadError, isTableDef, isTopologyEnvVar, isTransformableImage, isUncountedPath, isViewDef, json, lazyResource, listBackupObjects, listenWithPortRetry, loadBackendSchema, loadBootEnv, loadBundle, loadBundleProjectExports, loadBundleSchema, loadCronJobsFromDirectory, loadCronJobsWithDiagnostics, loadCrons, loadEnv, loadFunctions, loadFunctionsFromDirectory, loadFunctionsWithDiagnostics, logger, looksLikeFieldOp, mcpAppBaseUri, mcpViewToolInputSchema, oauthCodeFlowSchema, optionalAuth, overridableSecurityHeaders, parseBackupDestination, parseBackupTimestamp, parseFieldOp, parseTransformOptions, pendingBackgroundWork, pgEnum, pkceTokenParams, policy, providerVerifiedEmail, queryTokenAuth, raw, rawQueryLoggingEnabled, readBackupBytes, readBundleManifest, readUploadColumnContext, realtimeSocketPath, rebase, refuseUnhonouredImpersonation, registerDevEmailSink, registerResourceResolver, rel, reportSimulatedContext, requireAdmin, requireAuth, requireDriver, requireEnv, requireRole, requireScope, resolveApiKey, resolveAuthHooks, resolveAuthOptions, resolveBatchRefs, resolveConflictTarget, resolveCorsOrigin, resolveDataSources, resolveDeclaredTables, resolveEmailBranding, resolveEmailLinkBase, resolveEmailOptions, resolveModulePath, resolveRequireAuth, resolveStorageAccessControl, resolveStorageBackend, resolveStorageSources, resourceResolver, resourceResolvers, rowETag, runFromBundle, runtimeKey, safeCompare, schemaDriftRemedy, serveSPA, setDefaultBackend, setLogOutput, showAppArtifactGuide, splitFieldOps, sql, subscriptionIdOf, summarize as summarizeRlsScan, transformImage, tryVerifyOidcIdToken, unbindableKinds, validateApiKey, validateCronExpression, validatePasswordStrength, verifyCredential, verifyOidcIdToken, verifyPassword, versionColumn, versionedMcpAppUri, waitUntil, z };
35894
36922
 
35895
36923
  //# sourceMappingURL=index.es.js.map