@workbasehq/core 0.2.15 → 0.3.1

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 (96) hide show
  1. package/package.json +18 -3
  2. package/src/access-evaluator.ts +72 -0
  3. package/src/access-guards.ts +35 -0
  4. package/src/access-inputs.ts +62 -0
  5. package/src/access-lock/cli.ts +34 -0
  6. package/src/access-lock.ts +183 -0
  7. package/src/access.ts +209 -0
  8. package/src/account-action-conditions.ts +27 -0
  9. package/src/account-command.ts +8 -0
  10. package/src/admin-ui.tsx +3 -2
  11. package/src/app.ts +3 -3
  12. package/src/canonical.ts +6 -0
  13. package/src/capabilities.ts +5 -3
  14. package/src/commands.ts +14 -8
  15. package/src/config.ts +105 -69
  16. package/src/console-build.ts +37 -0
  17. package/src/console-contract.ts +4 -0
  18. package/src/console-model.ts +2 -0
  19. package/src/console.ts +3 -3
  20. package/src/crud.ts +13 -7
  21. package/src/dev-mailbox.ts +35 -0
  22. package/src/display-identity.ts +12 -0
  23. package/src/execution/atomic.ts +17 -3
  24. package/src/execution/policies.ts +14 -6
  25. package/src/execution/policy-receipts.ts +6 -5
  26. package/src/execution/post-commit.ts +11 -0
  27. package/src/execution/types.ts +1 -1
  28. package/src/index.ts +2 -0
  29. package/src/infra/README.md +39 -3
  30. package/src/infra/d1-migrations.ts +4 -3
  31. package/src/infra/instance-migrations.ts +26 -5
  32. package/src/infra/provision-config-main.mjs +3 -3
  33. package/src/infra/provision-diagnostics.ts +4 -0
  34. package/src/infra/provision-plan.ts +34 -5
  35. package/src/infra/provision.ts +26 -4
  36. package/src/infra/schema.ts +1 -1
  37. package/src/kernel/invitation-mail-port.ts +26 -0
  38. package/src/kernel/mail-outbox-port.ts +4 -2
  39. package/src/kernel/migrations.ts +38 -15
  40. package/src/kernel/plugin.ts +2 -0
  41. package/src/kernel/predicate.ts +15 -3
  42. package/src/kernel/registry.ts +69 -12
  43. package/src/member-bootstrap.ts +65 -0
  44. package/src/member-identities.ts +42 -0
  45. package/src/migrations/diagnostics.ts +6 -1
  46. package/src/migrations/model-b.ts +2 -1
  47. package/src/migrations/operational-evidence.ts +51 -0
  48. package/src/migrations/planner.ts +12 -1
  49. package/src/migrations/rebuild.ts +17 -12
  50. package/src/migrations/reset-era.ts +29 -0
  51. package/src/migrations/schema-bundle.ts +43 -0
  52. package/src/migrations/schema-cli.ts +74 -0
  53. package/src/migrations/schema-git.ts +36 -0
  54. package/src/migrations/schema-lock.ts +159 -0
  55. package/src/migrations/schema-plan.ts +94 -0
  56. package/src/migrations/schema.ts +73 -48
  57. package/src/migrations/sdk-baseline.ts +35 -0
  58. package/src/migrations/system-schema.ts +39 -0
  59. package/src/model-inputs.ts +25 -0
  60. package/src/openapi/cli.ts +72 -0
  61. package/src/openapi/generate.ts +166 -0
  62. package/src/openapi/input-projection.ts +131 -0
  63. package/src/openapi/public-paths.ts +80 -0
  64. package/src/openapi/routes.ts +29 -0
  65. package/src/ops.ts +4 -2
  66. package/src/organization-name.ts +35 -0
  67. package/src/organization-permissions.ts +10 -0
  68. package/src/organizations.ts +72 -3
  69. package/src/policies.ts +22 -6
  70. package/src/public-projection.ts +108 -0
  71. package/src/public-schema.ts +5 -43
  72. package/src/query/input-schema.ts +89 -0
  73. package/src/query/limits.ts +1 -1
  74. package/src/query/schema.ts +11 -89
  75. package/src/record-action-routes.ts +87 -0
  76. package/src/record-actions-data.ts +17 -0
  77. package/src/record-actions.ts +61 -0
  78. package/src/record-read.ts +20 -0
  79. package/src/row-access.ts +11 -0
  80. package/src/row-invitations.ts +29 -0
  81. package/src/schema/README.md +323 -0
  82. package/src/schema/declaration.ts +5 -0
  83. package/src/schema/load.ts +423 -0
  84. package/src/schema/lock-format.ts +117 -0
  85. package/src/schema/physical-names.ts +30 -0
  86. package/src/schema/revision.ts +16 -0
  87. package/src/schema/source-location.ts +3 -0
  88. package/src/schema-compatibility.ts +2 -2
  89. package/src/schema.ts +171 -0
  90. package/src/types.ts +1 -1
  91. package/src/user-link-eligibility.ts +36 -0
  92. package/src/user-links.ts +27 -16
  93. package/src/worker-access-actions.ts +89 -0
  94. package/src/worker-access.ts +61 -0
  95. package/src/workflow-runtime.ts +109 -22
  96. package/src/bootstrap.ts +0 -23
package/src/index.ts CHANGED
@@ -30,3 +30,5 @@ export { expand } from './config-shorthand'
30
30
 
31
31
  export { consumeEvents } from './event-delivery'
32
32
  export type { AuditOutboxRow } from './kernel/audit-port'
33
+
34
+ export * from './organization-name'
@@ -68,12 +68,13 @@ The API does not discover the account subdomain or generate an auth secret.
68
68
  | `configPath`, `handler`, `migrationsDir` | Required application-owned module, Worker entry and ordered SQL directory |
69
69
  | `resourcePrefix`, `stage` | Required lowercase DNS-style names; prefix ≤63, stage ≤32 characters |
70
70
  | `authSecret`, `authBaseUrl` | Required stable `Input<string>` secret and explicit HTTPS origin |
71
- | `assetsDir?` | Existing prebuilt console directory; absent means no `ASSETS` binding |
71
+ | `assetsDir?` | Built Instance console directory (normally `dist/console`) with verified SHA metadata; absent means no `ASSETS` binding |
72
72
  | `domain?` | Optional Cloudflare custom hostname matching the auth origin |
73
73
  | `email?: { from }` | Native `EMAIL` send binding restricted to this sender, plus `EMAIL_FROM` |
74
74
  | `webhook?: { url, allowedHosts, service?, events? }` | Explicit URL/host allowlist, optional existing Worker service name and event filter |
75
75
  | `internalToken?` | Optional secret `INTERNAL_TOKEN` for protected operations |
76
76
  | `opsToken?` | Optional secret `OPS_TOKEN` for protected operations; takes precedence over `INTERNAL_TOKEN` |
77
+ | `devMailbox?: { token }` | Opt-in separate credential-reading Worker, only for exact `dev`/`test` stages; returns `devMailboxUrl` |
77
78
  | `accountId?`, `projectRoot?` | Override account environment value or path root; SST normally runs in the app root |
78
79
  | `protect?` | Protect/retain primary resources; defaults to true for `production` |
79
80
  | `migrationTriggers?` | Extra fingerprints for imported application/plugin verification code |
@@ -102,13 +103,44 @@ a webhook receiver/landing Worker. All physical names and Pulumi logical names
102
103
  include the prefix/stage identity; long names retain a deterministic tuple hash.
103
104
  Worker names fit SST's 54-character workers.dev limit; other names fit 63 characters.
104
105
 
105
- The packaged `workbase-migrate` entry runs SQL and plugin migrations/verification
106
+ Before registering any resources, provisioning requires valid `build-meta.json`
107
+ with a 40-character lowercase SHA and build time. It verifies that SHA against
108
+ the `index.html` stamp and the complete emitted directory, including copied
109
+ `public/` assets. Missing/invalid metadata raises `provision_console_metadata_invalid`;
110
+ disagreeing HTML or file bytes raise `provision_console_sha_mismatch`. Run the
111
+ Instance's `bun run build:console` before retrying.
112
+
113
+ The packaged `workbase-migrate` entry runs SDK, plugin and domain migrations/verification
106
114
  before the Worker component **and** the underlying script upload. Inputs travel
107
115
  through quoted environment variables; credentials are inherited by the subprocess.
108
116
  SQL-chain hash, expected schema, package sources and config source fingerprint the
109
117
  migration command; use `migrationTriggers` when imported application verifier code
110
118
  changes independently. The migration command is unprotected so trigger changes can
111
119
  replace it, while production D1 and other primary resources remain protected.
120
+ New `defineConfig` Instances (identified by their declaration marker, never by `languages`) apply
121
+ `workbase-sdk` first, installed plugin namespaces next, then `migrations/`.
122
+ The SDK and plugins share `_plugin_migrations`, including append-only names,
123
+ positions, SQL checksums and retained uninstall receipts. Each file's SQL and
124
+ receipt commit in one D1 batch; a failed SDK/plugin file stops before domain SQL.
125
+ Verification, including plugin `checkSchema`, runs after the domain ledger.
126
+ A retry with no pending work executes only reads. SDK-only changes add SDK
127
+ receipts without changing the Instance revision or domain migration files.
128
+
129
+ The SDK baseline owns system/auth/workflow/operational tables, `instance_meta`
130
+ and the `users` account projection before any plugin or domain FK uses them.
131
+ Its SQL is independent of application roles and other Instance configuration;
132
+ the runtime validates roles. New-era `initialSchema(config)` emits domain DDL
133
+ and a domain revision insert only. Use `workbase-migrate ... --config ...` to
134
+ orchestrate all namespaces; applying domain SQL alone cannot bootstrap an Instance.
135
+
136
+ Existing tables or receipts without the new SDK baseline, or a legacy
137
+ `workbase-core` receipt, produce `migration_unsupported_history` with the found
138
+ tables/namespaces and an explicit unsupported/reset explanation. Preflight is
139
+ read-only: history is never copied, adopted or rewritten. A failed first SDK
140
+ file can leave an empty `_plugin_migrations` table and can be retried. The inline
141
+ `defineInstance` path retains its previous mixed baseline and deploy behavior
142
+ while its consumers are retired; it cannot serve as new-era migration history.
143
+
112
144
  The Worker receives the corresponding `SCHEMA_EXPECTED`.
113
145
  Migration failure blocks upload. A stable prefix/stage reuses resource addresses
114
146
  and receipts; changing either creates a separate instance.
@@ -128,7 +160,11 @@ This provisioner does not change SST state storage.
128
160
 
129
161
  Email requires an authorized Cloudflare sender. With magic-link login, configure
130
162
  working email delivery or another supported transport even on workers.dev. Omitting
131
- `email` does not provide a substitute login transport. Omitting `assetsDir` leaves
163
+ `email` alone does not provide a substitute login transport. For disposable dev/test
164
+ stages, explicitly opt into the [development mailbox sidecar](../../../../docs/sdk/dev-mailbox.md)
165
+ for operator-authorized outbox retrieval and first-owner onboarding. Its dedicated
166
+ secret is never bound to the application Worker; production cannot provision it.
167
+ Omitting `assetsDir` leaves
132
168
  the API available while the runtime reports `console_not_built` for the console.
133
169
 
134
170
  Offline tests verify the graph, dependency ordering and installed package bytes.
@@ -4,7 +4,7 @@ export interface Migration { filename: string; sql: string; checksum: string }
4
4
  export interface QueryResult { success: boolean; results?: Record<string, unknown>[] }
5
5
  export type D1Query = (sql: string) => Promise<QueryResult[]>
6
6
  const literal = (value: string) => `'${value.replaceAll("'", "''")}'`
7
- export async function migrateD1(query: D1Query, input: readonly Migration[]) {
7
+ export async function migrateD1(query: D1Query, input: readonly Migration[], receiptSQL: (migration: Migration) => string = () => '') {
8
8
  const migrations = [...input].sort((a, b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0)
9
9
  if (new Set(migrations.map(m => m.filename)).size !== migrations.length) throw new MigrationDiagnostic({ code: 'duplicate_migration_filename' })
10
10
  const execute: D1Query = async sql => {
@@ -12,7 +12,8 @@ export async function migrateD1(query: D1Query, input: readonly Migration[]) {
12
12
  if (!results.length || results.some(r => !r.success)) throw new MigrationDiagnostic({ code: 'd1_query_failed' })
13
13
  return results
14
14
  }
15
- await execute('CREATE TABLE IF NOT EXISTS _migrations (filename TEXT PRIMARY KEY, applied_at TEXT NOT NULL, checksum TEXT NOT NULL);')
15
+ const ledger = (await execute("SELECT name FROM sqlite_master WHERE type='table' AND name='_migrations'"))[0].results ?? []
16
+ if (!ledger.length) await execute('CREATE TABLE IF NOT EXISTS _migrations (filename TEXT PRIMARY KEY, applied_at TEXT NOT NULL, checksum TEXT NOT NULL);')
16
17
  const applied = (await execute('SELECT filename, checksum FROM _migrations ORDER BY filename;'))[0].results ?? []
17
18
  const known = new Map(migrations.map(m => [m.filename, m]))
18
19
  for (const row of applied) {
@@ -24,7 +25,7 @@ export async function migrateD1(query: D1Query, input: readonly Migration[]) {
24
25
  for (const migration of migrations) {
25
26
  if (done.has(migration.filename)) continue
26
27
  if (last && migration.filename < last) throw new MigrationDiagnostic({ code: 'migration_out_of_order', filename: migration.filename })
27
- await execute(`${migration.sql}\n;\nINSERT INTO _migrations (filename,applied_at,checksum) VALUES (${literal(migration.filename)},strftime('%Y-%m-%dT%H:%M:%fZ','now'),${literal(migration.checksum)});`)
28
+ await execute(`${migration.sql}\n;\n${receiptSQL(migration)}INSERT INTO _migrations (filename,applied_at,checksum) VALUES (${literal(migration.filename)},strftime('%Y-%m-%dT%H:%M:%fZ','now'),${literal(migration.checksum)});`)
28
29
  }
29
30
  return { applied: migrations.length - done.size, total: migrations.length }
30
31
  }
@@ -1,7 +1,9 @@
1
+ import { assertSchemaLockBound } from '../schema/revision'
2
+ import { assertResetEra, usesSdkBaseline } from '../migrations/reset-era'
1
3
  import { MigrationDiagnostic } from './diagnostics'
2
4
  import { CORE_VERSION } from '../config'
3
5
  import { hashMigrationRows } from '../schema-compatibility'
4
- import { coreVersionSQL, literal } from '../migrations/schema'
6
+ import { coreVersionSQL, revisionSQL, literal } from '../migrations/schema'
5
7
  import { pluginMigrationStatus } from '../kernel/migrations'
6
8
  import type { KernelRegistry } from '../kernel/registry'
7
9
  import { migrateD1, type D1Query, type Migration } from './d1-migrations'
@@ -48,23 +50,42 @@ function supportedCoreVersion(value: unknown) {
48
50
  (version[1] < current[1] || (version[1] === current[1] && version[2] <= current[2]))
49
51
  }
50
52
 
53
+ export const sdkStampSQL = '-- SDK stamp is owned by deployment.\n'
54
+
55
+ /** Shared by deployment and explicitly synthetic offline replay. */
56
+ export function instanceMigrationReceipt(sdk: boolean, migration: Migration) {
57
+ if (!sdk) return ''
58
+ const match = /^\d+_r([1-9]\d*)\.sql$/.exec(migration.filename)
59
+ if (!match || !Number.isSafeInteger(Number(match[1]))) throw new MigrationDiagnostic({ code: 'migration_instance_revision_mismatch' })
60
+ // Only the explicit SDK-only marker may reuse a revision. Ordinary domain
61
+ // files retain strict receipts, including rejection of planner-owned receipts.
62
+ const receipt = revisionSQL(Number(match[1]))
63
+ return (migration.sql === sdkStampSQL ? receipt.replace('INSERT INTO', 'INSERT OR IGNORE INTO') : receipt) + '\n'
64
+ }
65
+
51
66
  export async function migrateInstance(query: D1Query, files: readonly Migration[], kernel: KernelRegistry) {
67
+ assertSchemaLockBound(kernel.config)
52
68
  const db = queryDatabase(query)
69
+ const sdk = usesSdkBaseline(kernel.config)
70
+ if (sdk) await assertResetEra(db)
53
71
  const metaSQL = 'SELECT revision,core_version FROM instance_meta ORDER BY revision DESC LIMIT 1'
54
72
  // Check an existing database before even creating a ledger or applying SQL:
55
73
  // a pending SQL file could otherwise overwrite an unsupported SDK stamp.
56
74
  const existing = await db.prepare("SELECT name FROM sqlite_master WHERE name='instance_meta'").first()
57
75
  if (existing) {
58
76
  const stored = await db.prepare(metaSQL).first<{ core_version: string }>()
59
- if (!supportedCoreVersion(stored?.core_version)) throw new MigrationDiagnostic({ code: 'migration_instance_revision_mismatch' })
77
+ if ((stored || !sdk) && !supportedCoreVersion(stored?.core_version)) throw new MigrationDiagnostic({ code: 'migration_instance_revision_mismatch' })
60
78
  }
61
- const legacy = await migrateD1(query, files)
79
+ if (sdk) await kernel.applyMigrations(db)
80
+ const domain = await migrateD1(query, files, migration => {
81
+ return instanceMigrationReceipt(sdk, migration)
82
+ })
62
83
  const rows = await db.prepare('SELECT filename,checksum FROM _migrations ORDER BY filename').all<{ filename: string; checksum: string }>()
63
84
  const expectedRows = [...files].sort((a, b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0)
64
85
  if (await hashMigrationRows(rows.results) !== await hashMigrationRows(expectedRows)) throw new MigrationDiagnostic({ code: 'migration_instance_verification_failed' })
65
86
  const meta = await db.prepare(metaSQL).first<{ revision: number; core_version: string }>()
66
87
  if (meta?.revision !== kernel.config.revision || !supportedCoreVersion(meta.core_version)) throw new MigrationDiagnostic({ code: 'migration_instance_revision_mismatch' })
67
- await kernel.applyMigrations(db)
88
+ if (!sdk) await kernel.applyMigrations(db)
68
89
  const status = await pluginMigrationStatus(db, kernel.plugins, kernel.config)
69
90
  if (status.expected !== status.applied) throw new MigrationDiagnostic({ code: 'migration_plugin_verification_failed' })
70
91
  // A release can change CORE_VERSION without adding SQL or a config revision.
@@ -72,5 +93,5 @@ export async function migrateInstance(query: D1Query, files: readonly Migration[
72
93
  if (meta.core_version !== CORE_VERSION) await db.prepare(coreVersionSQL(kernel.config.revision)).run()
73
94
  const applied = await db.prepare(metaSQL).first<{ revision: number; core_version: string }>()
74
95
  if (applied?.revision !== kernel.config.revision || applied.core_version !== CORE_VERSION) throw new MigrationDiagnostic({ code: 'migration_instance_revision_mismatch' })
75
- return { ...legacy, pluginMigrations: status.applied }
96
+ return { ...domain, pluginMigrations: status.applied }
76
97
  }
@@ -15,8 +15,8 @@ async function main() {
15
15
  finish({ kind: 'invalid-config' })
16
16
  } else {
17
17
  try {
18
- // Keep plugin functions, schemas and identity brands in this process. Only
19
- // the resulting schema fingerprints cross the IPC boundary.
18
+ // Keep plugin functions and schemas in this process. Era is config data
19
+ // shared across both tsImport realms; only fingerprints cross IPC.
20
20
  const { tsImport } = await import('tsx/esm/api')
21
21
  const { expectedSchema } = await tsImport(new URL('./schema.ts', import.meta.url).href, import.meta.url)
22
22
  const schema = await expectedSchema({ migrationsDirectory, revision: config.revision, config })
@@ -26,4 +26,4 @@ async function main() {
26
26
  }
27
27
  }
28
28
  }
29
- await main()
29
+ await main().catch(error => finish({ kind: 'load-error', message: error instanceof Error ? error.message : String(error) }))
@@ -5,7 +5,9 @@ const codes = [
5
5
  'provision_invalid_config_path', 'provision_invalid_migrations_dir', 'provision_invalid_assets_dir',
6
6
  'provision_invalid_auth_secret', 'provision_invalid_auth_base_url', 'provision_invalid_domain',
7
7
  'provision_invalid_email', 'provision_invalid_webhook', 'provision_invalid_account_id',
8
+ 'provision_invalid_dev_mailbox_stage', 'provision_invalid_dev_mailbox_token',
8
9
  'provision_config_load_failed', 'provision_invalid_config', 'provision_inputs_unreadable',
10
+ 'provision_console_metadata_invalid', 'provision_console_sha_mismatch',
9
11
  'provision_requires_sst', 'provision_requires_command', 'provision_failed',
10
12
  ] as const
11
13
  export type ProvisionDiagnosticCode = typeof codes[number]
@@ -18,6 +20,8 @@ export class ProvisionDiagnostic extends Error {
18
20
  constructor(code: ProvisionDiagnosticCode, detail?: { message: string; secrets: string[] }) {
19
21
  const safeCode = codes.includes(code) ? code : 'provision_failed'
20
22
  let message: string = safeCode
23
+ if (safeCode === 'provision_console_metadata_invalid') message += ': console build-meta.json is missing or invalid; run build:console before provisioning'
24
+ if (safeCode === 'provision_console_sha_mismatch') message += ': console SHA does not match the HTML stamp and emitted artifacts; run build:console before provisioning'
21
25
  if (safeCode === 'provision_config_load_failed' && detail) {
22
26
  const secrets = Object.fromEntries(detail.secrets.map((value, index) => [`SECRET_${index}`, value]))
23
27
  const cause = redactCliOutput(detail.message, { ...process.env, ...secrets })
@@ -1,11 +1,14 @@
1
1
  import type { Input } from '@pulumi/pulumi'
2
+ import { createHash } from 'node:crypto'
2
3
  import { readFile, readdir, stat } from 'node:fs/promises'
3
4
  import { dirname, join, resolve } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
4
6
  import type { SchemaRevision } from '../schema-compatibility'
5
7
  import { migrationHash, readMigrationFiles, sha256 } from './migration-files'
6
8
  import { ProvisionDiagnostic, provisionFailure } from './provision-diagnostics'
7
9
  import { installedInfraDirectory } from './package-tools'
8
10
  import { provisionConfigSchema } from './provision-config'
11
+ import { consoleArtifactsSHA, consoleHTMLStamps, readConsoleArtifacts } from '../console-build'
9
12
 
10
13
  export interface ProvisionOptions {
11
14
  /** Trusted application module, default-exporting an InstanceConfig. Paths resolve from projectRoot. */
@@ -14,7 +17,7 @@ export interface ProvisionOptions {
14
17
  migrationsDir: string
15
18
  resourcePrefix: string
16
19
  stage: string
17
- /** Prebuilt console directory. Omit for an API-only Worker. */
20
+ /** Built Instance console directory with verified SHA metadata. Omit for an API-only Worker. */
18
21
  assetsDir?: string
19
22
  /** Stable, operator-supplied secret, e.g. new sst.Secret('AuthSecret').value. Never generated per deploy. */
20
23
  authSecret: Input<string>
@@ -26,6 +29,8 @@ export interface ProvisionOptions {
26
29
  internalToken?: Input<string>
27
30
  /** Secret OPS_TOKEN for protected operations; takes precedence over INTERNAL_TOKEN. */
28
31
  opsToken?: Input<string>
32
+ /** Opt-in, separate credential-reading Worker. Only the exact dev and test stages are permitted. */
33
+ devMailbox?: { token: Input<string> }
29
34
  /** Defaults to CLOUDFLARE_DEFAULT_ACCOUNT_ID. Credentials stay in the deploy environment. */
30
35
  accountId?: string
31
36
  /** Defaults to the SST app root (process.cwd() inside SST run()). */
@@ -49,6 +54,7 @@ export interface ProvisionPlan {
49
54
  schema: SchemaRevision
50
55
  environment: Record<string, string>
51
56
  bindingNames: string[]
57
+ devMailbox?: { name: string; handler: string; bindingNames: string[] }
52
58
  migration: { command: string; bin: string; triggers: string[] }
53
59
  }
54
60
 
@@ -60,6 +66,10 @@ function label(value: unknown, limit: number): value is string {
60
66
  /** No values supplied by callers are included in validation messages. */
61
67
  export function validateProvisionOptions(options: ProvisionOptions): void {
62
68
  if (!options || !label(options.stage, 32)) throw new ProvisionDiagnostic('provision_invalid_stage')
69
+ if (options.devMailbox !== undefined) {
70
+ if (options.stage !== 'dev' && options.stage !== 'test') throw new ProvisionDiagnostic('provision_invalid_dev_mailbox_stage')
71
+ if (!options.devMailbox?.token || (typeof options.devMailbox.token === 'string' && !/^[\x21-\x7e]{32,256}$/.test(options.devMailbox.token))) throw new ProvisionDiagnostic('provision_invalid_dev_mailbox_token')
72
+ }
63
73
  if (!label(options.resourcePrefix, 63)) throw new ProvisionDiagnostic('provision_invalid_prefix')
64
74
  if (!nonempty(options.handler)) throw new ProvisionDiagnostic('provision_invalid_handler')
65
75
  if (!nonempty(options.configPath)) throw new ProvisionDiagnostic('provision_invalid_config_path')
@@ -84,7 +94,7 @@ export function validateProvisionOptions(options: ProvisionOptions): void {
84
94
  function resourceName(prefix: string, stage: string, suffix: string) {
85
95
  const hash = sha256(JSON.stringify([prefix, stage, suffix])).slice(0, 12)
86
96
  const stem = `${prefix}-${stage}-${suffix}`
87
- const limit = suffix === 'worker' ? 54 : 63
97
+ const limit = suffix === 'worker' || suffix === 'dev-mailbox' ? 54 : 63
88
98
  return `${stem.slice(0, limit - hash.length - 1).replace(/-+$/, '')}-${hash}`
89
99
  }
90
100
 
@@ -114,10 +124,28 @@ export async function createProvisionPlan(options: ProvisionOptions): Promise<Pr
114
124
  try {
115
125
  if (!(await stat(handler)).isFile() || !(await stat(configPath)).isFile() || !(await stat(migrationsDir)).isDirectory() || (assetsDir && !(await stat(assetsDir)).isDirectory())) throw 0
116
126
  } catch { throw new ProvisionDiagnostic('provision_inputs_unreadable') }
117
- const secrets = [options.authSecret, options.internalToken, options.opsToken, options.webhook?.url, options.webhook?.allowedHosts, options.webhook?.service]
127
+ if (assetsDir) {
128
+ let files: Map<string, Buffer>, metadata: { sha?: unknown; builtAt?: unknown }
129
+ try {
130
+ files = await readConsoleArtifacts(assetsDir)
131
+ metadata = JSON.parse(files.get('build-meta.json')!.toString('utf8'))
132
+ if (!metadata || typeof metadata.sha !== 'string' || !/^[a-f0-9]{40}$/.test(metadata.sha)
133
+ || typeof metadata.builtAt !== 'string' || !Number.isFinite(Date.parse(metadata.builtAt))) throw 0
134
+ } catch { throw new ProvisionDiagnostic('provision_console_metadata_invalid') }
135
+ const stamps = consoleHTMLStamps(files.get('index.html')?.toString('utf8') ?? '')
136
+ if (stamps.length !== 1 || stamps[0] !== metadata.sha || consoleArtifactsSHA(files) !== metadata.sha
137
+ || [...files].some(([name, bytes]) => name.endsWith('.html') && consoleHTMLStamps(bytes.toString('utf8')).some(sha => sha !== metadata.sha))) {
138
+ throw new ProvisionDiagnostic('provision_console_sha_mismatch')
139
+ }
140
+ }
141
+ const secrets = [options.authSecret, options.internalToken, options.opsToken, options.devMailbox?.token, options.webhook?.url, options.webhook?.allowedHosts, options.webhook?.service]
118
142
  .filter((value): value is string => typeof value === 'string' && value.length > 0)
119
143
  const schema = await provisionConfigSchema(root, configPath, migrationsDir, secrets)
120
144
  try {
145
+ // Older consumers without the artifact retain provisioning; live verification fails closed.
146
+ let openapi = 'unbuilt'
147
+ try { openapi = createHash('sha256').update(await readFile(join(dirname(configPath), 'openapi.json'))).digest('hex') }
148
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error }
121
149
  const files = await readMigrationFiles(migrationsDir)
122
150
  const tools = await packageTools()
123
151
  const name = (suffix: string) => resourceName(options.resourcePrefix, options.stage, suffix)
@@ -125,12 +153,13 @@ export async function createProvisionPlan(options: ProvisionOptions): Promise<Pr
125
153
  stage: options.stage, root, configPath, handler, migrationsDir, ...(assetsDir ? { assetsDir } : {}),
126
154
  names: { database: name('db'), audit: name('audit'), events: name('events'), deadLetter: name('events-dlq'), worker: name('worker') },
127
155
  id: `Workbase${sha256(JSON.stringify([options.resourcePrefix, options.stage])).slice(0, 20)}`,
156
+ ...(options.devMailbox ? { devMailbox: { name: name('dev-mailbox'), handler: fileURLToPath(import.meta.resolve('@workbasehq/core/dev-mailbox')), bindingNames: ['DB', 'STAGE', 'DEV_MAILBOX_TOKEN'] } } : {}),
128
157
  schema,
129
- environment: { STAGE: options.stage, SCHEMA_EXPECTED: JSON.stringify(schema), AUTH_BASE_URL: options.authBaseUrl,
158
+ environment: { STAGE: options.stage, SCHEMA_EXPECTED: JSON.stringify(schema), OPENAPI_SHA256: openapi, AUTH_BASE_URL: options.authBaseUrl,
130
159
  ...(options.email ? { EMAIL_FROM: options.email.from } : {}),
131
160
  ...(options.webhook?.events ? { WEBHOOK_EVENTS: options.webhook.events } : {}),
132
161
  },
133
- bindingNames: ['DB', 'AUDIT_KV', 'EVENTS_QUEUE', 'BETTER_AUTH_SECRET', 'AUTH_BASE_URL', 'STAGE', 'SCHEMA_EXPECTED',
162
+ bindingNames: ['DB', 'AUDIT_KV', 'EVENTS_QUEUE', 'BETTER_AUTH_SECRET', 'AUTH_BASE_URL', 'STAGE', 'SCHEMA_EXPECTED', 'OPENAPI_SHA256',
134
163
  ...(assetsDir ? ['ASSETS'] : []), ...(options.email ? ['EMAIL', 'EMAIL_FROM'] : []),
135
164
  ...(options.webhook ? ['WEBHOOK_URL', 'WEBHOOK_ALLOWED_HOSTS', ...(options.webhook.service ? ['WEBHOOK_SERVICE'] : []), ...(options.webhook.events ? ['WEBHOOK_EVENTS'] : [])] : []),
136
165
  ...(options.internalToken ? ['INTERNAL_TOKEN'] : []),
@@ -22,9 +22,11 @@ export interface ProvisionResult {
22
22
  databaseId: Output<string>
23
23
  eventsQueueName: Output<string>
24
24
  deadLetterQueueName: Output<string>
25
+ devMailboxUrl?: Output<string | undefined>
25
26
  resources: {
26
27
  database: DatabaseResource; audit: KvResource; events: QueueResource; deadLetter: QueueResource
27
28
  migrations: local.Command; worker: WorkerResource; consumer: import('@pulumi/pulumi').Resource; cron: CronResource
29
+ devMailbox?: WorkerResource
28
30
  }
29
31
  }
30
32
 
@@ -61,9 +63,10 @@ export async function provision(options: ProvisionOptions): Promise<ProvisionRes
61
63
  triggers: [...plan.migration.triggers, ...(options.migrationTriggers ?? [])],
62
64
  }, { protect: false, dependsOn: [db, db.nodes.database] })
63
65
 
64
- function secret(value: Input<string>, auth = false) {
66
+ function secret(value: Input<string>, kind?: 'auth' | 'mailbox') {
65
67
  return $util.secret($util.output(value).apply(text => {
66
- if (auth && (typeof text !== 'string' || text.length < 32)) throw new ProvisionDiagnostic('provision_invalid_auth_secret')
68
+ if (kind === 'auth' && (typeof text !== 'string' || text.length < 32)) throw new ProvisionDiagnostic('provision_invalid_auth_secret')
69
+ if (kind === 'mailbox' && (typeof text !== 'string' || !/^[\x21-\x7e]{32,256}$/.test(text))) throw new ProvisionDiagnostic('provision_invalid_dev_mailbox_token')
67
70
  return text
68
71
  }))
69
72
  }
@@ -71,7 +74,7 @@ export async function provision(options: ProvisionOptions): Promise<ProvisionRes
71
74
  { name: 'DB', type: 'd1', id: db.databaseId },
72
75
  { name: 'AUDIT_KV', type: 'kv_namespace', namespaceId: audit.namespaceId },
73
76
  { name: 'EVENTS_QUEUE', type: 'queue', queueName: events.nodes.queue.queueName },
74
- { name: 'BETTER_AUTH_SECRET', type: 'secret_text', text: secret(options.authSecret, true) },
77
+ { name: 'BETTER_AUTH_SECRET', type: 'secret_text', text: secret(options.authSecret, 'auth') },
75
78
  ...(options.internalToken ? [{ name: 'INTERNAL_TOKEN', type: 'secret_text', text: secret(options.internalToken) }] : []),
76
79
  ...(options.opsToken ? [{ name: 'OPS_TOKEN', type: 'secret_text', text: secret(options.opsToken) }] : []),
77
80
  ...(options.webhook ? [
@@ -105,10 +108,29 @@ export async function provision(options: ProvisionOptions): Promise<ProvisionRes
105
108
  const cron = new cloudflare.WorkersCronTrigger(`${plan.id}RelayCron`, {
106
109
  accountId, scriptName: worker.nodes.worker.scriptName, schedules: [{ cron: '*/5 * * * *' }],
107
110
  }, { ...protection, dependsOn: [worker] })
111
+ // A separate entry and resource, constructed only after the strict dev/test gate.
112
+ // It receives no application auth/ops secrets, assets, routes, queue or cron.
113
+ const devMailbox = plan.devMailbox && options.devMailbox ? new sst.cloudflare.Worker(`${plan.id}DevMailbox`, {
114
+ accountId, handler: plan.devMailbox.handler, url: true, dev: false,
115
+ compatibility: { date: '2026-08-01', flags: ['nodejs_compat'] },
116
+ environment: { STAGE: plan.stage },
117
+ transform: { worker: (args, opts) => {
118
+ args.scriptName = plan.devMailbox!.name
119
+ args.keepBindings = []
120
+ args.observability = { enabled: true, headSamplingRate: 1, logs: { enabled: true, invocationLogs: false, persist: true } }
121
+ args.bindings = $util.output({ existing: args.bindings, token: secret(options.devMailbox!.token, 'mailbox'), databaseId: db.databaseId })
122
+ .apply(({ existing, token, databaseId }) => [...(existing ?? []),
123
+ { name: 'DB', type: 'd1', id: databaseId }, { name: 'DEV_MAILBOX_TOKEN', type: 'secret_text', text: token },
124
+ ])
125
+ Object.assign(opts, protection)
126
+ opts.dependsOn = [migrations]
127
+ } },
128
+ }, { ...protection, dependsOn: [migrations] }) : undefined
108
129
  return {
109
130
  stage: plan.stage, url: worker.url, workerName: worker.nodes.worker.scriptName, databaseId: db.databaseId,
110
131
  eventsQueueName: events.nodes.queue.queueName, deadLetterQueueName: deadLetter.nodes.queue.queueName,
111
- resources: { database: db, audit, events, deadLetter, migrations, worker, consumer, cron },
132
+ ...(devMailbox ? { devMailboxUrl: devMailbox.url } : {}),
133
+ resources: { database: db, audit, events, deadLetter, migrations, worker, consumer, cron, ...(devMailbox ? { devMailbox } : {}) },
112
134
  }
113
135
  } catch (error) { throw provisionFailure(error) }
114
136
  }
@@ -16,6 +16,6 @@ export async function expectedSchema({ migrationsDirectory, revision, config, co
16
16
  const plugins = config ? new KernelRegistry(config).plugins : []
17
17
  return {
18
18
  revision, coreVersion, migrations: migrationHash(await readMigrationFiles(migrationsDirectory)),
19
- ...(config ? { pluginMigrations: sha256(JSON.stringify(await expectedPluginMigrations(plugins))) } : {}),
19
+ ...(config ? { pluginMigrations: sha256(JSON.stringify(await expectedPluginMigrations(plugins, config))) } : {}),
20
20
  }
21
21
  }
@@ -0,0 +1,26 @@
1
+ import type { InstanceConfig } from '../config'
2
+ import type { RuntimeEnv } from '../types'
3
+ import type { GuardedStatement } from '../execution/types'
4
+
5
+ export interface InvitationMailOptions {
6
+ inviterId: string; role: string; expiresAt: string; kind: 'invite' | 'reminder'
7
+ /** Bind delivery to the exact committed invitation, plus the caller's live row guard. */
8
+ invitationId?: string
9
+ eligible?: () => Promise<boolean>
10
+ /** Local development only; production destination always comes from configuration. */
11
+ localFallback?: string
12
+ }
13
+ export interface InvitationDeliveryStatus {
14
+ status: string; attempts: number; sent_at: string | null; error: string | null
15
+ }
16
+ /** Members owns rendering and delivered-email credentials; core only orchestrates. */
17
+ export interface InvitationMailPort {
18
+ /** Unsigned management link: recipient sign-in is still required. */
19
+ copyLink(env: RuntimeEnv, selector: string, localFallback?: string): Promise<string>
20
+ prepare(env: RuntimeEnv, config: InstanceConfig, outboxId: string, organizationId: string, recipient: string, selector: string,
21
+ options: InvitationMailOptions): Promise<{
22
+ intent(expiresAt: string): GuardedStatement
23
+ deliver(): Promise<void>
24
+ }>
25
+ status(env: RuntimeEnv, config: InstanceConfig, outboxId: string | null): Promise<InvitationDeliveryStatus>
26
+ }
@@ -13,11 +13,13 @@ export interface MailStatus {
13
13
  id: string; delivery_status: 'pending' | 'sending' | 'sent' | 'failed'
14
14
  attempts: number; sent_at: string | null; last_error: string | null
15
15
  }
16
+ /** Runtime-only finalization; returned credentials go directly to the transport. */
17
+ export type MailDeliveryRenderer = (message: { body: string; text: string; html: string }) => Promise<{ text: string; html: string; subject?: string }>
16
18
  export interface MailOutboxPort {
17
19
  /** Include this statement in the caller's transaction; guard preserves mutation chaining. */
18
20
  intent(message: MailIntent, guard?: string): GuardedStatement
19
21
  status(db: D1Database, id: string): Promise<MailStatus | null>
20
22
  /** Caller must revalidate the live credential, scope and operation before every attempt. */
21
- deliver(env: RuntimeEnv, config: InstanceConfig, id: string, eligible: () => Promise<boolean>): Promise<void>
22
- retry(env: RuntimeEnv, config: InstanceConfig, id: string, eligible: () => Promise<boolean>): Promise<void>
23
+ deliver(env: RuntimeEnv, config: InstanceConfig, id: string, eligible: () => Promise<boolean>, render?: MailDeliveryRenderer): Promise<void>
24
+ retry(env: RuntimeEnv, config: InstanceConfig, id: string, eligible: () => Promise<boolean>, render?: MailDeliveryRenderer): Promise<void>
23
25
  }
@@ -1,12 +1,24 @@
1
+ import { sdkMigrations, SDK_NAMESPACE } from '../migrations/sdk-baseline'
2
+ import { assertResetEra, usesSdkBaseline, type MigrationConfig } from '../migrations/reset-era'
1
3
  import { coreMigrations } from '../migrations/model-b'
4
+ import { internalMigrationMessage } from '../migrations/diagnostics'
2
5
  import { sha256 } from '../crypto'
3
6
  import type { WorkbasePlugin } from './plugin'
4
7
  import type { InstanceConfig } from '../config'
5
8
 
9
+ /** Preserve the failing step even when statement generation fails before SQL. */
10
+ export class PluginMigrationError extends Error {
11
+ constructor(readonly namespace: string, readonly migration: string, cause: unknown) {
12
+ super(`Plugin migration ${namespace}/${migration} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
13
+ }
14
+ }
15
+
6
16
  /** Per-plugin append-only ledgers. Absent namespaces are retained on uninstall. */
7
17
  export async function applyPluginMigrations(db: D1Database, plugins: readonly WorkbasePlugin[], config?: InstanceConfig) {
8
- await db.prepare('CREATE TABLE IF NOT EXISTS _plugin_migrations (namespace TEXT NOT NULL, name TEXT NOT NULL, position INTEGER NOT NULL, checksum TEXT NOT NULL, PRIMARY KEY(namespace,name), UNIQUE(namespace,position))').run()
9
- for (const plugin of ledgerPlugins(plugins, config)) {
18
+ const chain = ledgerPlugins(plugins, config)
19
+ const exists = usesSdkBaseline(config) && await assertResetEra(db)
20
+ if (!exists) await db.prepare('CREATE TABLE IF NOT EXISTS _plugin_migrations (namespace TEXT NOT NULL, name TEXT NOT NULL, position INTEGER NOT NULL, checksum TEXT NOT NULL, PRIMARY KEY(namespace,name), UNIQUE(namespace,position))').run()
21
+ for (const plugin of chain) {
10
22
  const migrations = plugin.migrations ?? []
11
23
  const { results: applied } = await db.prepare('SELECT name,position,checksum FROM _plugin_migrations WHERE namespace=? ORDER BY position').bind(plugin.name).all<{ name: string; position: number; checksum: string }>()
12
24
  const checksums = await Promise.all(migrations.map(m => sha256(m.sql)))
@@ -19,15 +31,20 @@ export async function applyPluginMigrations(db: D1Database, plugins: readonly Wo
19
31
  // D1 batch is transactional. SQL is supplied as statements by trusted plugins.
20
32
  // exec supports multi-statement SQL but is not transactional with the ledger;
21
33
  // prepare/batch keeps DDL, data changes and their ledger entry atomic.
22
- const sql = migration.statements ? (await migration.statements(db)).flatMap(splitStatements) : splitStatements(migration.sql)
23
- const statements = sql.map(statement => db.prepare(statement))
24
- await db.batch([...statements, db.prepare('INSERT INTO _plugin_migrations (namespace,name,position,checksum) VALUES (?,?,?,?)').bind(plugin.name, migration.name, position, checksums[position])])
34
+ try {
35
+ const sql = migration.statements ? (await migration.statements(db)).flatMap(splitStatements) : splitStatements(migration.sql)
36
+ const statements = sql.map(statement => db.prepare(statement))
37
+ await db.batch([...statements, db.prepare('INSERT INTO _plugin_migrations (namespace,name,position,checksum) VALUES (?,?,?,?)').bind(plugin.name, migration.name, position, checksums[position])])
38
+ } catch (error) {
39
+ if (internalMigrationMessage(error)) throw error
40
+ throw new PluginMigrationError(plugin.name, migration.name, error)
41
+ }
25
42
  }
26
43
  }
27
44
  }
28
45
 
29
46
  /** Split SQL without treating semicolons in quoted strings/comments as boundaries. */
30
- function splitStatements(sql: string): string[] {
47
+ export function splitStatements(sql: string): string[] {
31
48
  const statements: string[] = []
32
49
  let trigger = false; let bodyStatementStart = false; let words: string[] = []
33
50
  let start = 0; let depth = 0; let hasCode = false; let quote = ''; let lineComment = false; let blockComment = false
@@ -62,14 +79,17 @@ function splitStatements(sql: string): string[] {
62
79
  }
63
80
 
64
81
  export interface PluginMigrationRow { namespace: string; name: string; position: number; checksum: string }
65
- export async function expectedPluginMigrations(plugins: readonly WorkbasePlugin[]): Promise<PluginMigrationRow[]> {
66
- const rows = await Promise.all(ledgerPlugins(plugins).flatMap(plugin => (plugin.migrations ?? []).map(async (migration, position) => ({ namespace: plugin.name, name: migration.name, position, checksum: await sha256(migration.sql) }))))
82
+ export async function expectedPluginMigrations(plugins: readonly WorkbasePlugin[], config?: MigrationConfig): Promise<PluginMigrationRow[]> {
83
+ const rows = await Promise.all(ledgerPlugins(plugins, config).flatMap(plugin => (plugin.migrations ?? []).map(async (migration, position) => ({ namespace: plugin.name, name: migration.name, position, checksum: await sha256(migration.sql) }))))
67
84
  return rows.sort((a, b) => a.namespace < b.namespace ? -1 : a.namespace > b.namespace ? 1 : a.position - b.position)
68
85
  }
69
- export async function pluginMigrationStatus(db: D1Database, plugins: readonly WorkbasePlugin[], config: Pick<InstanceConfig, 'entities'>) {
70
- for (const plugin of plugins) await plugin.checkSchema?.(db, config)
71
- const expected = await expectedPluginMigrations(plugins)
72
- const names = new Set(ledgerPlugins(plugins).map(plugin => plugin.name))
86
+ export async function pluginMigrationStatus(db: D1Database, plugins: readonly WorkbasePlugin[], config: MigrationConfig) {
87
+ for (const plugin of plugins) {
88
+ try { await plugin.checkSchema?.(db, config) }
89
+ catch (error) { throw new PluginMigrationError(plugin.name, 'checkSchema', error) }
90
+ }
91
+ const expected = await expectedPluginMigrations(plugins, config)
92
+ const names = new Set(ledgerPlugins(plugins, config).map(plugin => plugin.name))
73
93
  const { results } = await db.prepare('SELECT namespace,name,position,checksum FROM _plugin_migrations ORDER BY namespace,position').all<PluginMigrationRow>()
74
94
  // Uninstalled namespaces remain on disk but cannot satisfy installed contracts.
75
95
  const applied = results.filter(row => names.has(row.namespace))
@@ -78,7 +98,10 @@ export async function pluginMigrationStatus(db: D1Database, plugins: readonly Wo
78
98
  }
79
99
 
80
100
  /** Reserved core namespace shares the same transaction and verification contract. */
81
- function ledgerPlugins(plugins: readonly WorkbasePlugin[], config?: InstanceConfig): readonly WorkbasePlugin[] {
82
- if (plugins.some(plugin => plugin.name === 'workbase-core')) throw new Error('Reserved migration namespace: workbase-core')
83
- return [{ name: 'workbase-core', version: '1.0.0', migrations: coreMigrations(config) }, ...plugins]
101
+ function ledgerPlugins(plugins: readonly WorkbasePlugin[], config?: MigrationConfig): readonly WorkbasePlugin[] {
102
+ for (const name of ['workbase-core', SDK_NAMESPACE]) if (plugins.some(plugin => plugin.name === name)) throw new Error(`Reserved migration namespace: ${name}`)
103
+ const sdk = usesSdkBaseline(config)
104
+ ? { name: SDK_NAMESPACE, version: '1.0.0', migrations: sdkMigrations() }
105
+ : { name: 'workbase-core', version: '1.0.0', migrations: coreMigrations(config as InstanceConfig | undefined) }
106
+ return [sdk, ...plugins]
84
107
  }
@@ -1,5 +1,6 @@
1
1
  import type { ConsoleContribution, ConsoleRegistry } from '../console-contract'
2
2
  import type { IdentityPort, ProfileSynchronization } from './identity-port'
3
+ import type { InvitationMailPort } from './invitation-mail-port'
3
4
  import type { MailOutboxPort } from './mail-outbox-port'
4
5
  import type { AuditPort } from './audit-port'
5
6
  import type { ZodType } from 'zod'
@@ -69,6 +70,7 @@ export interface WorkbasePlugin {
69
70
  /** Profile synchronization policy declared by an external login adapter. */
70
71
  profileAuthority?: { provider: string; synchronization: ProfileSynchronization }
71
72
  mailOutbox?: MailOutboxPort
73
+ invitationMail?: InvitationMailPort
72
74
  audit?: AuditPort
73
75
  contributes?: { console?: ConsoleContribution }
74
76
  /** Console provider owns registry validation and actor projection. */
@@ -3,6 +3,18 @@ import type { Predicate, PredicateActorLink, PredicateRelation, PredicateValue,
3
3
 
4
4
  export class PolicyExpansionLimit extends Error {}
5
5
 
6
+ /** Group adjacent rendered leaves without changing their order or Boolean scope.
7
+ * Explicit binary parentheses keep wide groups below D1's expression-depth cap. */
8
+ function renderBooleanGroup(parts: string[], operator: 'AND' | 'OR'): string {
9
+ if (parts.length <= 1) return `(${parts[0] ?? (operator === 'AND' ? '1=1' : '0=1')})`
10
+ function range(start: number, end: number): string {
11
+ if (end - start === 1) return parts[start]
12
+ const middle = start + Math.floor((end - start) / 2)
13
+ return `(${range(start, middle)} ${operator} ${range(middle, end)})`
14
+ }
15
+ return range(0, parts.length)
16
+ }
17
+
6
18
  /** Expand every related source before separating mandatory request authority from
7
19
  * row selection. Both read and pre/post-image compilers consume this same tree;
8
20
  * renderers must not introduce another table policy inside a quantifier. */
@@ -64,7 +76,7 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
64
76
  if (entries.length !== 1) throw new Error('Invalid predicate combinator')
65
77
  const [key, children] = logical as ['all' | 'any', Predicate[]]
66
78
  const all = (key === 'all') !== negated
67
- return `(${children.length ? children.map(child => render(child, negated)).join(all ? ' AND ' : ' OR ') : all ? '1=1' : '0=1'})`
79
+ return renderBooleanGroup(children.map(child => render(child, negated)), all ? 'AND' : 'OR')
68
80
  }
69
81
  if (Object.hasOwn(node, 'not')) {
70
82
  if (entries.length !== 1) throw new Error('Invalid predicate combinator')
@@ -99,7 +111,7 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
99
111
  quote(relation.entity); quote(relation.field); quote(relation.parentField)
100
112
  return `(${renderRelation(relation, tableAlias, (relationKey === 'notExists') !== negated)})`
101
113
  }
102
- const scalar = `(${entries.flatMap(([field, operators]) => {
114
+ const scalar = renderBooleanGroup(entries.flatMap(([field, operators]) => {
103
115
  const column = `${alias}.${quote(field)}`
104
116
  if (!operators || typeof operators !== 'object' || Array.isArray(operators) || !Object.keys(operators).length) throw new Error('Invalid predicate operator')
105
117
  return Object.entries(operators).map(([op, value]) => {
@@ -127,7 +139,7 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
127
139
  if (!sqlOp || !Object.hasOwn({ eq: 1, ne: 1, lt: 1, lte: 1, gt: 1, gte: 1 }, op)) throw new Error('Invalid predicate operator')
128
140
  return `${column}${sqlOp}${bind(value)}`
129
141
  })
130
- }).join(' AND ')})`
142
+ }), 'AND')
131
143
  return negated ? `(NOT ${scalar})` : scalar
132
144
  }
133
145
  return { sql: render(predicate), bindings }