@workbasehq/core 0.2.15 → 0.3.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 (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
@@ -0,0 +1,423 @@
1
+ import { createHash } from 'node:crypto'
2
+ /** Build-time source validation only: keep Node and the TS compiler out of runtime imports. */
3
+ import { readFileSync, existsSync, realpathSync, readdirSync, statSync } from 'node:fs'
4
+ import { dirname, extname, isAbsolute, resolve, relative } from 'node:path'
5
+ import { fileURLToPath, URL } from 'node:url'
6
+ import ts from 'typescript'
7
+ import { accountLink, DeclarationError, defineConfig, defineEntity, defineAccess, bindSchemaLock } from '../schema'
8
+ import type { InstanceConfig } from '../config'
9
+ import type { AccessInput, EntityAccess } from '../access'
10
+ import { parseLock } from '../migrations/schema-lock'
11
+ import type { SourceLocation, SourceMap } from './source-location'
12
+ export type { SourceLocation, SourceMap } from './source-location'
13
+
14
+ export class SourceError extends Error {
15
+ constructor(readonly location: SourceLocation, message: string) {
16
+ super(`${location.file}:${location.line}:${location.column}: ${message}`)
17
+ this.name = 'SourceError'
18
+ }
19
+ }
20
+ function location(node: ts.Node): SourceLocation {
21
+ const file = node.getSourceFile()
22
+ const pos = file.getLineAndCharacterOfPosition(node.getStart(file))
23
+ return { file: file.fileName, line: pos.line + 1, column: pos.character + 1 }
24
+ }
25
+ function fail(node: ts.Node, message: string): never { throw new SourceError(location(node), message) }
26
+ function readSource(file: string) {
27
+ const text = readFileSync(file, 'utf8')
28
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
29
+ // Syntax errors the host would reject must never yield an interpreted config.
30
+ const [diagnostic] = ts.transpileModule(text, { fileName: file, reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.Latest } }).diagnostics ?? []
31
+ if (diagnostic) {
32
+ const pos = diagnostic.start === undefined ? { line: 0, character: 0 } : source.getLineAndCharacterOfPosition(diagnostic.start)
33
+ throw new SourceError({ file, line: pos.line + 1, column: pos.character + 1 }, ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
34
+ }
35
+ return source
36
+ }
37
+ function unwrap(node: ts.Expression): ts.Expression {
38
+ return ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isTypeAssertionExpression(node) ? unwrap(node.expression) : node
39
+ }
40
+ function key(node: ts.PropertyName): string {
41
+ if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return node.text
42
+ return fail(node, 'Computed property names are outside the literal boundary')
43
+ }
44
+ function properties(node: ts.ObjectLiteralExpression) {
45
+ const entries = new Map<string, ts.ObjectLiteralElementLike>()
46
+ for (const property of node.properties) {
47
+ if (!property.name) fail(property, 'Spread is outside the literal boundary')
48
+ const name = key(property.name)
49
+ if (name === '__proto__') fail(property, '__proto__ is outside the literal boundary')
50
+ if (entries.has(name)) fail(property, `Duplicate literal property: ${name}`)
51
+ entries.set(name, property)
52
+ }
53
+ return entries
54
+ }
55
+ function value(node: ts.ObjectLiteralElementLike | undefined): ts.Expression | undefined {
56
+ if (!node) return undefined
57
+ if (ts.isPropertyAssignment(node)) return unwrap(node.initializer)
58
+ if (ts.isShorthandPropertyAssignment(node)) return node.name
59
+ return fail(node, 'Expected a property assignment')
60
+ }
61
+ interface Binding { module: string; imported: string; node: ts.StringLiteral }
62
+ function imports(file: ts.SourceFile, statements: readonly ts.Statement[] = file.statements) {
63
+ const bindings = new Map<string, Binding>()
64
+ const add = (name: string, binding: Binding) => {
65
+ if (bindings.has(name)) fail(binding.node, `Duplicate import binding: ${name}`)
66
+ bindings.set(name, binding)
67
+ }
68
+ for (const statement of statements) {
69
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly) continue
70
+ const clause = statement.importClause
71
+ if (clause?.name) add(clause.name.text, { node: statement.moduleSpecifier, module: statement.moduleSpecifier.text, imported: 'default' })
72
+ if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const item of clause.namedBindings.elements) {
73
+ if (!item.isTypeOnly) add(item.name.text, { node: statement.moduleSpecifier, module: statement.moduleSpecifier.text, imported: (item.propertyName ?? item.name).text })
74
+ }
75
+ }
76
+ return bindings
77
+ }
78
+ /** Bare SDK imports are syntax; local SDK imports must identify the canonical file. */
79
+ export function sdkBinding(binding: Binding | undefined, file: string, name: string, sdkModule = '@workbasehq/core/schema', sdkFile = fileURLToPath(new URL('../schema.ts', import.meta.url))) {
80
+ if (binding?.imported !== name) return false
81
+ if (binding.module === sdkModule) return true
82
+ if (!binding.module.startsWith('./') && !binding.module.startsWith('../') && !isAbsolute(binding.module)) return false
83
+ const path = resolve(dirname(file), binding.module)
84
+ const candidates = extname(path) ? [path] : [path, `${path}.ts`]
85
+ const files: string[] = []
86
+ try {
87
+ for (const candidate of candidates) {
88
+ try {
89
+ // Direct files only: directories never imply an index or package lookup.
90
+ if (statSync(candidate).isFile()) files.push(realpathSync(candidate))
91
+ } catch (error) {
92
+ if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error
93
+ }
94
+ }
95
+ if (files.length > 1) fail(binding.node, `Ambiguous SDK import: ${binding.module}`)
96
+ if (!files.length) fail(binding.node, `Cannot resolve SDK import: ${binding.module}`)
97
+ return files[0] === realpathSync(sdkFile)
98
+ } catch (error) {
99
+ if (error instanceof SourceError) throw error
100
+ return fail(binding.node, `Cannot resolve SDK import: ${binding.module}`)
101
+ }
102
+ }
103
+ /** Entity resolution is deliberately independent of host extension/index precedence. */
104
+ function entityPath(binding: Binding, entry: string, name: string, directory = 'schema'): string {
105
+ const prefix = directory ? `./${directory}/` : './'
106
+ if (![`${prefix}${name}`, `${prefix}${name}.ts`].includes(binding.module) || /[/\\]/.test(name)) fail(binding.node, 'Entity import must match schema/<entity>.ts')
107
+ try {
108
+ const schema = realpathSync(resolve(dirname(entry), directory))
109
+ // Reject competing imports, excluding the two generated access audit artifacts.
110
+ const lower = name.toLowerCase()
111
+ if (readdirSync(schema).some(candidate => candidate !== `${name}.ts`
112
+ && !(directory === '' && name === 'access' && ['access.lock.json', 'access.lock.md'].includes(candidate))
113
+ && (candidate.toLowerCase() === lower || candidate.toLowerCase().startsWith(lower + '.')))) fail(binding.node, 'Ambiguous entity import: competing schema candidate')
114
+ const path = realpathSync(resolve(schema, `${name}.ts`))
115
+ if (dirname(path) !== schema) fail(binding.node, 'Resolved entity import must match schema/<entity>.ts inside the schema directory')
116
+ return path
117
+ } catch (error) {
118
+ if (error instanceof SourceError) throw error
119
+ return fail(binding.node, 'Cannot resolve entity import')
120
+ }
121
+ }
122
+ /** Resolve a known runtime config import without treating config.* siblings as entities. */
123
+ function runtimeConfigPath(binding: Binding, entry: string): string {
124
+ const project = dirname(entry)
125
+ const path = resolve(project, binding.module)
126
+ const candidates = extname(path) ? [path] : [path, `${path}.ts`]
127
+ try {
128
+ const files = candidates.filter(candidate => {
129
+ try { return statSync(candidate).isFile() }
130
+ catch (error) {
131
+ if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return false
132
+ throw error
133
+ }
134
+ })
135
+ if (files.length > 1) fail(binding.node, `Ambiguous config import: ${binding.module}`)
136
+ if (!files.length) fail(binding.node, `Cannot resolve config import: ${binding.module}`)
137
+ const config = realpathSync(files[0])
138
+ if (dirname(config) !== project) fail(binding.node, 'Resolved config import must stay inside the project directory')
139
+ return config
140
+ } catch (error) {
141
+ if (error instanceof SourceError) throw error
142
+ return fail(binding.node, `Cannot resolve config import: ${binding.module}`)
143
+ }
144
+ }
145
+ /** Only these statements and imports belong to the declaration syntax. */
146
+ function moduleBoundary(file: ts.SourceFile, declaration: ts.Expression, helpers: string[], entityImports = new Set<string>(), isSdk = sdkBinding) {
147
+ for (const statement of file.statements) {
148
+ if (ts.isImportDeclaration(statement)) {
149
+ const clause = statement.importClause
150
+ if (!clause || !ts.isStringLiteral(statement.moduleSpecifier) || statement.attributes) fail(statement, 'Expected a direct named SDK or entity import')
151
+ if (clause.isTypeOnly) continue
152
+ if (!clause.name && clause.namedBindings && ts.isNamedImports(clause.namedBindings)
153
+ && clause.namedBindings.elements.length > 0 && clause.namedBindings.elements.every(item => item.isTypeOnly)) continue
154
+ if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)) fail(statement, 'Expected direct named imports')
155
+ const names = [...imports(file, [statement]).entries()]
156
+ if (!names.length) fail(statement, 'Expected a direct named SDK or entity import')
157
+ for (const [local, binding] of names) {
158
+ if (entityImports.has(local)) continue
159
+ if (!helpers.some(name => isSdk(binding, file.fileName, name))) fail(statement, 'Expected a direct named SDK or entity import')
160
+ }
161
+ continue
162
+ }
163
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals && unwrap(statement.expression) === declaration) continue
164
+ if (ts.isVariableStatement(statement) && statement.modifiers?.length === 1 && statement.modifiers[0].kind === ts.SyntaxKind.ExportKeyword
165
+ && statement.declarationList.flags === ts.NodeFlags.Const && statement.declarationList.declarations.length === 1
166
+ && statement.declarationList.declarations[0].initializer && unwrap(statement.declarationList.declarations[0].initializer!) === declaration) continue
167
+ fail(statement, 'Expected only imports and one direct declaration export')
168
+ }
169
+ }
170
+ function exported(file: ts.SourceFile, name: string): ts.Expression | undefined {
171
+ if (name === 'default') {
172
+ const statement = file.statements.find(ts.isExportAssignment)
173
+ if (statement && !statement.isExportEquals) return unwrap(statement.expression)
174
+ }
175
+ for (const statement of file.statements) {
176
+ if (!ts.isVariableStatement(statement) || !statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue
177
+ for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === name && declaration.initializer) return unwrap(declaration.initializer)
178
+ }
179
+ }
180
+ function index(node: ts.Expression, path: string, sources: SourceMap) {
181
+ node = unwrap(node)
182
+ sources[path] = location(node)
183
+ if (ts.isObjectLiteralExpression(node)) for (const [name, property] of properties(node)) {
184
+ const child = [path, name].filter(Boolean).join('.')
185
+ const expression = value(property)
186
+ if (expression) index(expression, child, sources)
187
+ sources[child] = location(property)
188
+ }
189
+ if (ts.isArrayLiteralExpression(node)) node.elements.forEach((element, i) => index(element, `${path}.${i}`, sources))
190
+ }
191
+ function nearest(sources: SourceMap, path: string): SourceLocation {
192
+ while (!sources[path] && path) path = path.split('.').slice(0, -1).join('.')
193
+ return sources[path] ?? sources['']
194
+ }
195
+ function remap(error: unknown, sources: SourceMap, prefix = ''): never {
196
+ if (error instanceof SourceError) throw error
197
+ if (error instanceof DeclarationError) throw new SourceError(nearest(sources, [prefix, ...error.path].filter(part => part !== '').join('.')), error.message)
198
+ throw new SourceError(nearest(sources, prefix), error instanceof Error ? error.message : String(error))
199
+ }
200
+ /** Evaluate only literal syntax already accepted by the boundary, never JavaScript code. */
201
+ function literal(node: ts.Expression, bindings: Map<string, Binding>, path: string[] = [], isSdk = sdkBinding): unknown {
202
+ node = unwrap(node)
203
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text
204
+ if (ts.isNumericLiteral(node)) return Number(node.text)
205
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true
206
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false
207
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null
208
+ if (ts.isPrefixUnaryExpression(node) && [ts.SyntaxKind.MinusToken, ts.SyntaxKind.PlusToken].includes(node.operator) && ts.isNumericLiteral(node.operand)) return (node.operator === ts.SyntaxKind.MinusToken ? -1 : 1) * Number(node.operand.text)
209
+ if (ts.isArrayLiteralExpression(node)) return node.elements.map((element, i) => literal(element, bindings, [...path, String(i)], isSdk))
210
+ if (ts.isObjectLiteralExpression(node)) {
211
+ // Plain objects, as JavaScript evaluation of the same literal would produce.
212
+ const result: Record<string, unknown> = {}
213
+ for (const property of node.properties) {
214
+ if (ts.isSpreadAssignment(property)) fail(property, 'Spread is outside the literal boundary')
215
+ if (!ts.isPropertyAssignment(property)) fail(property, 'Expected a literal property assignment; no variables, methods or accessors')
216
+ const name = key(property.name)
217
+ if (name === '__proto__') fail(property, '__proto__ is outside the literal boundary')
218
+ if (Object.hasOwn(result, name)) fail(property, `Duplicate literal property: ${name}`)
219
+ result[name] = literal(property.initializer, bindings, [...path, name], isSdk)
220
+ }
221
+ return result
222
+ }
223
+ if (ts.isCallExpression(node)) {
224
+ if (path.join('.') === 'fields.user' && ts.isIdentifier(node.expression)
225
+ && isSdk(bindings.get(node.expression.text), node.getSourceFile().fileName, 'accountLink') && !node.arguments.length && !node.typeArguments?.length) return accountLink()
226
+ return fail(node, 'Function call is outside the literal boundary; only SDK accountLink() at fields.user is allowed')
227
+ }
228
+ return fail(node, 'Expected a literal value; variables and expressions are outside the literal boundary')
229
+ }
230
+
231
+ /** Source metadata only, for trusted executable configs with SDK/plugin registrations.
232
+ * No evaluation, access compilation or policy inference occurs here. Imported code
233
+ * guards are attributed to their enclosing config registration unless mapped directly.
234
+ */
235
+ export function configSources(file: string, options: LoadConfigOptions = {}): SourceMap {
236
+ const entry = realpathSync(resolve(file))
237
+ const isSdk: typeof sdkBinding = (binding, file, name, ...args) => sdkBinding(binding,
238
+ options.sdkResolutionRoot ? resolve(options.sdkResolutionRoot, relative(dirname(entry), file)) : file, name, ...args)
239
+ const source = readSource(entry)
240
+ const sources: SourceMap = { '': location(source) }
241
+ let declaration = exported(source, 'default')
242
+ const bindings = imports(source)
243
+ // V3 runtime composition inherits its authored declarations from ./config.
244
+ // Keep audit locations identical whether callers supply config.ts or runtime.ts.
245
+ if (declaration && ts.isObjectLiteralExpression(declaration)) {
246
+ const spread = declaration.properties.find(ts.isSpreadAssignment)
247
+ const binding = spread && ts.isIdentifier(spread.expression) ? bindings.get(spread.expression.text) : undefined
248
+ if (binding?.imported === 'default' && ['./config', './config.ts'].includes(binding.module)) {
249
+ const config = runtimeConfigPath(binding, entry)
250
+ if (config !== entry) return configSources(config, options)
251
+ }
252
+ }
253
+ while (declaration && ts.isCallExpression(declaration) && ts.isIdentifier(declaration.expression)) {
254
+ const binding = bindings.get(declaration.expression.text)
255
+ if (!['bindOpenApi', 'bindSchemaLock'].some(name => isSdk(binding, entry, name))) break
256
+ declaration = declaration.arguments[0]
257
+ }
258
+ if (!declaration || !ts.isCallExpression(declaration) || !declaration.arguments[0]) return sources
259
+ // Code registrations may contain methods, calls and spreads. Index their
260
+ // enclosing declarations without applying the data-only literal validator.
261
+ const members = (node: ts.ObjectLiteralExpression) => node.properties.filter((property): property is ts.PropertyAssignment | ts.ShorthandPropertyAssignment =>
262
+ (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) && !ts.isComputedPropertyName(property.name))
263
+ function record(node: ts.Expression, prefix: string) {
264
+ node = unwrap(node)
265
+ sources[prefix] = location(node)
266
+ if (ts.isObjectLiteralExpression(node)) for (const property of members(node)) {
267
+ const child = [prefix, key(property.name)].filter(Boolean).join('.')
268
+ record(ts.isPropertyAssignment(property) ? property.initializer : property.name, child)
269
+ sources[child] = location(property)
270
+ }
271
+ if (ts.isArrayLiteralExpression(node)) node.elements.forEach((child, i) => record(child, `${prefix}.${i}`))
272
+ }
273
+ const arg = unwrap(declaration.arguments[0])
274
+ record(arg, '')
275
+ if (!ts.isObjectLiteralExpression(arg)) return sources
276
+ const props = new Map(members(arg).map(property => [key(property.name), property]))
277
+ const refs: [string, ts.Expression | undefined][] = [['access', value(props.get('access'))]]
278
+ const entities = value(props.get('entities'))
279
+ if (entities && ts.isObjectLiteralExpression(entities)) for (const property of members(entities)) refs.push([`entities.${key(property.name)}`, value(property)])
280
+ for (const [prefix, ref] of refs) {
281
+ if (!ref || !ts.isIdentifier(ref)) continue
282
+ const binding = bindings.get(ref.text)
283
+ if (!binding || !binding.module.startsWith('./')) continue
284
+ const name = prefix === 'access' ? 'access' : prefix.slice('entities.'.length)
285
+ const path = entityPath(binding, entry, name, prefix === 'access' ? '' : 'schema')
286
+ const imported = readSource(path)
287
+ const call = exported(imported, binding.imported)
288
+ if (call && ts.isCallExpression(call) && call.arguments[0]) record(call.arguments[0], prefix)
289
+ }
290
+ return sources
291
+ }
292
+
293
+ /** Identify V3 declarations without evaluating consumer code or artifact imports. */
294
+ export function isLiteralConfig(file: string): boolean {
295
+ const source = readSource(file)
296
+ return [...imports(source).values()].some(binding => sdkBinding(binding, file, 'defineConfig'))
297
+ }
298
+
299
+ export interface LoadConfigOptions {
300
+ /** Fresh initialization must ignore existing artifacts, including invalid/partial locks. */
301
+ bindExistingLock?: boolean
302
+ /** Original config directory when interpreting a staged graph. Only SDK import
303
+ * resolution moves; graph reads, source locations and hashes retain staged bytes. */
304
+ sdkResolutionRoot?: string
305
+ }
306
+
307
+ /**
308
+ * Interpret literal declarations and return the one kernel schema without executing
309
+ * consumer modules or asking the host runtime to resolve their imports.
310
+ * config.ts must default-export defineConfig({...}); its entity map explicitly imports
311
+ * default or named defineEntity({...}) exports from schema/<entity>.ts.
312
+ * Legacy defineInstance remains available through its existing runtime entry.
313
+ */
314
+ export async function loadConfig(file: string, options: LoadConfigOptions = {}): Promise<{ config: InstanceConfig; sources: SourceMap; configHash: string; authoredAccess: { shared?: AccessInput; entities: Record<string, EntityAccess | undefined> } }> {
315
+ const entry = realpathSync(resolve(file))
316
+ const isSdk: typeof sdkBinding = (binding, file, name, ...args) => sdkBinding(binding,
317
+ options.sdkResolutionRoot ? resolve(options.sdkResolutionRoot, relative(dirname(entry), file)) : file, name, ...args)
318
+ const readSet = new Map<string, string>()
319
+ const read = (file: string) => {
320
+ const source = readSource(file)
321
+ readSet.set(file, source.text)
322
+ return source
323
+ }
324
+ const source = read(entry)
325
+ const sources: SourceMap = { '': location(source) }
326
+ const bindings = imports(source)
327
+ const exportedConfig = exported(source, 'default')
328
+ let declaration = exportedConfig
329
+ let specImport: string | undefined
330
+ if (declaration && ts.isCallExpression(declaration) && ts.isIdentifier(declaration.expression)
331
+ && isSdk(bindings.get(declaration.expression.text), entry, 'bindOpenApi')) {
332
+ const [inner, spec] = declaration.arguments
333
+ const binding = spec && ts.isIdentifier(spec) ? bindings.get(spec.text) : undefined
334
+ if (declaration.arguments.length !== 2 || !inner || binding?.module !== './openapi.json' || binding.imported !== 'default') fail(declaration, 'bindOpenApi requires a config and an imported ./openapi.json')
335
+ specImport = (spec as ts.Identifier).text
336
+ declaration = unwrap(inner)
337
+ }
338
+ let lockImport: string | undefined
339
+ if (declaration && ts.isCallExpression(declaration) && ts.isIdentifier(declaration.expression)
340
+ && isSdk(bindings.get(declaration.expression.text), entry, 'bindSchemaLock')) {
341
+ const [inner, lock] = declaration.arguments
342
+ const binding = lock && ts.isIdentifier(lock) ? bindings.get(lock.text) : undefined
343
+ if (declaration.arguments.length !== 2 || !inner || binding?.module !== './schema.lock.json' || binding.imported !== 'default') fail(declaration, 'bindSchemaLock requires defineConfig({...}) and an imported ./schema.lock.json')
344
+ lockImport = (lock as ts.Identifier).text
345
+ declaration = unwrap(inner)
346
+ }
347
+ if (!declaration || !ts.isCallExpression(declaration) || !ts.isIdentifier(declaration.expression)) fail(source, 'Config must default-export a direct SDK defineConfig({...}) call')
348
+ if (!isSdk(bindings.get(declaration.expression.text), entry, 'defineConfig')) fail(declaration, 'Expected a direct named SDK defineConfig import')
349
+ const arg = declaration.arguments[0]
350
+ if (declaration.arguments.length !== 1 || !arg || !ts.isObjectLiteralExpression(unwrap(arg))) fail(declaration, 'defineConfig requires a literal object')
351
+ const config = unwrap(arg) as ts.ObjectLiteralExpression
352
+ index(config, '', sources)
353
+ const props = properties(config)
354
+ const entityMap = value(props.get('entities'))
355
+ if (!entityMap || !ts.isObjectLiteralExpression(entityMap)) fail(entityMap ?? config, 'entities must explicitly import schema/<entity>.ts declarations')
356
+ const entityImports = new Set<string>()
357
+ for (const property of properties(entityMap).values()) {
358
+ const ref = value(property)
359
+ if (!ref || !ts.isIdentifier(ref)) fail(ref ?? property, 'Entity must be an explicit schema import')
360
+ entityImports.add(ref.text)
361
+ }
362
+ const accessRef = value(props.get('access'))
363
+ if (accessRef) {
364
+ if (!ts.isIdentifier(accessRef)) fail(accessRef, 'access must be imported from ./access.ts')
365
+ entityImports.add(accessRef.text)
366
+ }
367
+ if (lockImport) entityImports.add(lockImport)
368
+ if (specImport) entityImports.add(specImport)
369
+ // The generated spec is never read here: missing/stale artifacts must remain repairable,
370
+ // and hashing the artifact would make its embedded configHash self-referential.
371
+ moduleBoundary(source, exportedConfig!, ['defineConfig', 'bindSchemaLock', 'bindOpenApi'], entityImports, isSdk)
372
+ const data: Record<string, unknown> = Object.create(null)
373
+ for (const [name, property] of props) if (name !== 'entities' && name !== 'access') data[name] = literal(value(property)!, new Map(), [], isSdk)
374
+ if (accessRef && ts.isIdentifier(accessRef)) {
375
+ const binding = bindings.get(accessRef.text)
376
+ if (!binding || !['./access', './access.ts'].includes(binding.module)) fail(accessRef, 'access must be imported from ./access.ts')
377
+ const path = entityPath(binding, entry, 'access', '')
378
+ const accessSource = read(path)
379
+ const expression = exported(accessSource, binding.imported)
380
+ const accessBindings = imports(accessSource)
381
+ if (!expression || !ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression)
382
+ || !isSdk(accessBindings.get(expression.expression.text), path, 'defineAccess')) fail(accessSource, 'Expected an exported defineAccess({...}) declaration')
383
+ const arg = expression.arguments[0]
384
+ if (expression.arguments.length !== 1 || !arg || !ts.isObjectLiteralExpression(unwrap(arg))) fail(expression, 'defineAccess requires a literal object')
385
+ moduleBoundary(accessSource, expression, ['defineAccess'], new Set(), isSdk)
386
+ index(arg, 'access', sources)
387
+ try { data.access = defineAccess(literal(arg, accessBindings, [], isSdk) as Parameters<typeof defineAccess>[0]) } catch (error) { remap(error, sources, 'access') }
388
+ }
389
+ const entities: Record<string, ReturnType<typeof defineEntity>> = Object.create(null)
390
+ for (const [name, property] of properties(entityMap)) {
391
+ if (name === 'users') fail(property, 'users is SDK-owned; use accountLink()')
392
+ const ref = value(property) as ts.Identifier
393
+ const binding = bindings.get(ref.text)
394
+ if (!binding?.module.startsWith('./schema/')) fail(ref, 'Entity must be imported from schema/<entity>.ts')
395
+ if (![`./schema/${name}`, `./schema/${name}.ts`].includes(binding.module)) fail(ref, 'Entity import must match schema/<entity>.ts')
396
+ const path = entityPath(binding, entry, name)
397
+ const entitySource = read(path)
398
+ const entityBindings = imports(entitySource)
399
+ const expression = exported(entitySource, binding.imported)
400
+ if (!expression || !ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression)
401
+ || !isSdk(entityBindings.get(expression.expression.text), path, 'defineEntity')) fail(entitySource, 'Expected an exported defineEntity({...}) declaration')
402
+ const entity = expression.arguments[0]
403
+ if (expression.arguments.length !== 1 || !entity || !ts.isObjectLiteralExpression(unwrap(entity))) fail(expression, 'defineEntity requires a literal object')
404
+ const prefix = `entities.${name}`
405
+ const entityData = literal(entity, entityBindings, [], isSdk)
406
+ moduleBoundary(entitySource, expression, ['defineEntity', 'accountLink'], new Set(), isSdk)
407
+ index(unwrap(entity), prefix, sources)
408
+ try { entities[name] = defineEntity(entityData as Parameters<typeof defineEntity>[0]) } catch (error) { remap(error, sources, prefix) }
409
+ }
410
+ try {
411
+ const config = defineConfig({ ...data, entities } as Parameters<typeof defineConfig>[0])
412
+ const hash = createHash('sha256')
413
+ for (const [file, text] of [...readSet].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
414
+ hash.update(JSON.stringify([relative(dirname(entry), file), text]))
415
+ }
416
+ const lockPath = resolve(dirname(entry), 'schema.lock.json')
417
+ if (options.bindExistingLock !== false && existsSync(lockPath)) bindSchemaLock(config, parseLock(readFileSync(lockPath, 'utf8')))
418
+ return { config, sources, configHash: hash.digest('hex'), authoredAccess: {
419
+ ...(data.access ? { shared: data.access as AccessInput } : {}),
420
+ entities: Object.fromEntries(Object.entries(entities).map(([name, entity]) => [name, entity.access])),
421
+ } }
422
+ } catch (error) { return remap(error, sources) }
423
+ }
@@ -0,0 +1,117 @@
1
+ import { z } from 'zod'
2
+ import type { TableSpec } from '../migrations/schema'
3
+
4
+ export interface FieldLineage { id: string; logicalName: string; physicalName: string }
5
+ export interface EntityLineage extends FieldLineage { fields: FieldLineage[] }
6
+ export interface RenameTransition {
7
+ id: string
8
+ entityId: string
9
+ fieldIds?: string[]
10
+ from: { logical: string; physical: string }
11
+ to: { logical: string; physical: string }
12
+ /** field = dual_column; entity = view. No bridge SQL is emitted yet. */
13
+ bridge: 'field' | 'entity'
14
+ phase: 'expanded' | 'switched' | 'contracted'
15
+ }
16
+ export interface SchemaLock {
17
+ lockVersion: 2; revision: number; parent: string | null; tables: TableSpec[]
18
+ entities: EntityLineage[]; transitions: RenameTransition[]
19
+ }
20
+
21
+ const name = z.string().regex(/^[a-z][a-z0-9_]*$/)
22
+ const entityId = z.string().regex(/^ent_[a-z0-9_]+$/)
23
+ const fieldId = z.string().regex(/^fld_[a-z0-9_]+$/)
24
+ const column = z.strictObject({
25
+ name, sqlType: z.enum(['TEXT', 'INTEGER', 'REAL']), notNull: z.boolean(), defaultSql: z.string().nullable(), checks: z.array(z.string()),
26
+ implicit: z.boolean().optional(), primaryKey: z.boolean().optional(), references: z.strictObject({ table: name, column: name }).optional(),
27
+ })
28
+ const table = z.strictObject({
29
+ name, columns: z.array(column), unique: z.array(z.array(name)), checks: z.array(z.string()),
30
+ foreignKeys: z.array(z.strictObject({ columns: z.array(name), table: name, targetColumns: z.array(name) })),
31
+ indexes: z.array(z.strictObject({ name, columns: z.array(name) })),
32
+ })
33
+ const header = { revision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), parent: z.string().regex(/^[a-f0-9]{64}$/).nullable(), tables: z.array(table) }
34
+ const field = z.strictObject({ id: fieldId, logicalName: name, physicalName: name })
35
+ const names = z.strictObject({ logical: name, physical: name })
36
+ const format = z.discriminatedUnion('lockVersion', [
37
+ z.strictObject({ lockVersion: z.literal(1), ...header }),
38
+ z.strictObject({ lockVersion: z.literal(2), ...header,
39
+ entities: z.array(z.strictObject({ id: entityId, logicalName: name, physicalName: name, fields: z.array(field) })),
40
+ transitions: z.array(z.strictObject({ id: z.string().regex(/^tr_[a-z0-9_]+$/), entityId, fieldIds: z.array(fieldId).length(1).optional(), from: names, to: names, bridge: z.enum(['field', 'entity']), phase: z.enum(['expanded', 'switched', 'contracted']) })),
41
+ }),
42
+ ])
43
+ // Injective encoding, rather than random IDs or a platform-specific hash. The
44
+ // initial physical path is an identity seed only; IDs never follow later names.
45
+ const seed = (value: string) => Array.from(value, c => c.charCodeAt(0).toString(16).padStart(2, '0')).join('')
46
+ export const initialEntityId = (physicalName: string) => `ent_${seed(physicalName)}`
47
+ export const initialFieldId = (entityId: string, physicalName: string) => `fld_${entityId.slice(4)}_${seed(physicalName)}`
48
+ export const transitionId = (entityId: string, fieldId: string | undefined, from: string, to: string, generation: number) => `tr_${entityId.slice(4)}_${fieldId?.slice(4) ?? 'entity'}_${seed(from)}_${seed(to)}_${generation}`
49
+ export function initialLineage(tables: readonly TableSpec[]): EntityLineage[] {
50
+ return tables.map(table => {
51
+ const id = initialEntityId(table.name)
52
+ return { id, logicalName: table.name, physicalName: table.name, fields: table.columns.map(column => ({ id: initialFieldId(id, column.name), logicalName: column.name, physicalName: column.name })) }
53
+ })
54
+ }
55
+ const invalid = (reason: string): never => { throw new Error(`Invalid schema.lock.json: ${reason}`) }
56
+ function unique(values: string[], label: string) {
57
+ if (new Set(values).size !== values.length) invalid(`duplicate ${label}`)
58
+ }
59
+ /** Worker-safe validation and deterministic v1 bootstrap; no IO, SQL or crypto. */
60
+ export function validateLock(input: unknown): SchemaLock {
61
+ const parsed = format.safeParse(input)
62
+ if (!parsed.success) return invalid(parsed.error.issues[0].message)
63
+ const value = parsed.data
64
+ const lock: SchemaLock = value.lockVersion === 1
65
+ ? { ...value, lockVersion: 2, entities: initialLineage(value.tables), transitions: [] }
66
+ : value
67
+ unique(lock.tables.map(t => t.name), 'physical table')
68
+ unique(lock.entities.map(e => e.id), 'entity ID')
69
+ unique(lock.entities.flatMap(e => e.fields.map(f => f.id)), 'field ID')
70
+ unique(lock.entities.map(e => e.logicalName), 'logical entity')
71
+ unique(lock.entities.map(e => e.physicalName), 'physical entity')
72
+ if (lock.entities.length !== lock.tables.length) invalid('lineage must cover every physical table')
73
+ for (const entity of lock.entities) {
74
+ const table = lock.tables.find(t => t.name === entity.physicalName)
75
+ if (!table) invalid(`missing physical table for ${entity.id}`)
76
+ unique(table!.columns.map(c => c.name), 'physical column')
77
+ unique(entity.fields.map(f => f.logicalName), 'logical field')
78
+ unique(entity.fields.map(f => f.physicalName), 'physical field')
79
+ if (entity.fields.length !== table!.columns.length || entity.fields.some(f => !table!.columns.some(c => c.name === f.physicalName))) invalid(`lineage must cover every physical column of ${entity.id}`)
80
+ }
81
+ unique(lock.transitions.map(t => t.id), 'transition ID')
82
+ const open = new Set<string>()
83
+ const history = new Map<string, RenameTransition>()
84
+ const aliases = new Map<string, string>()
85
+ for (const transition of lock.transitions) {
86
+ const entity = lock.entities.find(e => e.id === transition.entityId)
87
+ if (!entity) invalid(`unknown transition entity ${transition.entityId}`)
88
+ if (open.has(transition.entityId)) invalid(`second open transition for ${transition.entityId}`)
89
+ if (transition.phase !== 'contracted') open.add(transition.entityId)
90
+ if (transition.from.logical === transition.to.logical || transition.from.physical === transition.to.physical) invalid(`transition ${transition.id} must rename both logical and physical names`)
91
+ const target = transition.bridge === 'field' ? entity!.fields.find(f => f.id === transition.fieldIds?.[0]) : entity
92
+ if (!target || (transition.bridge === 'entity' && transition.fieldIds !== undefined)) invalid(`invalid fieldIds for transition ${transition.id}`)
93
+ if (transition.bridge === 'field' && lock.tables.find(t => t.name === entity!.physicalName)!.columns.find(c => c.name === target!.physicalName)?.implicit) invalid('implicit fields cannot be renamed')
94
+ const peers = transition.bridge === 'field' ? entity!.fields : lock.entities
95
+ for (const peer of peers) if (peer.id !== target!.id && [transition.from.logical, transition.to.logical].includes(peer.logicalName)) invalid(`logical collision in transition ${transition.id}`)
96
+ for (const peer of peers) if (peer.id !== target!.id && [transition.from.physical, transition.to.physical].includes(peer.physicalName)) invalid(`physical collision in transition ${transition.id}`)
97
+ // Historical aliases belong to the original ID, even after contraction.
98
+ // Reassigning one would make stored names ambiguous for future readers.
99
+ for (const side of [transition.from, transition.to]) for (const kind of ['logical', 'physical'] as const) {
100
+ const alias = `${transition.bridge === 'field' ? entity!.id : 'entities'}:${kind}:${side[kind]}`
101
+ const owner = aliases.get(alias)
102
+ if (owner && owner !== target!.id) invalid(`historical name collision in transition ${transition.id}`)
103
+ aliases.set(alias, target!.id)
104
+ }
105
+ const key = `${transition.bridge}:${target!.id}`
106
+ const previous = history.get(key)
107
+ if (previous && (previous.phase !== 'contracted' || previous.to.logical !== transition.from.logical || previous.to.physical !== transition.from.physical)) invalid(`broken history for transition ${transition.id}`)
108
+ history.set(key, transition)
109
+ }
110
+ for (const transition of history.values()) {
111
+ const entity = lock.entities.find(e => e.id === transition.entityId)!
112
+ const target = transition.bridge === 'field' ? entity.fields.find(f => f.id === transition.fieldIds![0])! : entity
113
+ const expected = transition.phase === 'expanded' ? transition.from : transition.to
114
+ if (target.logicalName !== expected.logical || target.physicalName !== expected.physical) invalid(`mapping disagrees with transition ${transition.id}`)
115
+ }
116
+ return lock
117
+ }
@@ -0,0 +1,30 @@
1
+ import { validateLock } from './lock-format'
2
+
3
+ /** Snapshot a validated lock. Public names locate immutable IDs; SQL consumers
4
+ * resolve those IDs to the pinned physical names. No compiler is rewired yet. */
5
+ export function createPhysicalNameResolver(input: unknown) {
6
+ const lock = validateLock(input)
7
+ const entity = (id: string) => {
8
+ const found = lock.entities.find(e => e.id === id)
9
+ if (!found) throw new Error(`Unknown entity ID: ${id}`)
10
+ return found
11
+ }
12
+ return {
13
+ entityId(logicalName: string): string {
14
+ const found = lock.entities.find(e => e.logicalName === logicalName)
15
+ if (!found) throw new Error(`Unknown logical entity: ${logicalName}`)
16
+ return found.id
17
+ },
18
+ fieldId(entityId: string, logicalName: string): string {
19
+ const found = entity(entityId).fields.find(f => f.logicalName === logicalName)
20
+ if (!found) throw new Error(`Unknown logical field: ${entityId}.${logicalName}`)
21
+ return found.id
22
+ },
23
+ table(entityId: string): string { return entity(entityId).physicalName },
24
+ column(entityId: string, fieldId: string): string {
25
+ const found = entity(entityId).fields.find(f => f.id === fieldId)
26
+ if (!found) throw new Error(`Unknown field ID: ${entityId}.${fieldId}`)
27
+ return found.physicalName
28
+ },
29
+ }
30
+ }
@@ -0,0 +1,16 @@
1
+ import { MigrationDiagnostic } from '../migrations/diagnostics'
2
+ import type { InstanceConfig } from '../config'
3
+ import { validateLock } from './lock-format'
4
+
5
+ /** Bind lock data before exporting a runtime config; safe in Worker bundles (no IO). */
6
+ export function bindSchemaLock<T extends InstanceConfig>(config: T, lock: unknown): T {
7
+ if (config.baseline !== 'workbase-sdk') throw new Error('Schema locks require a workbase-sdk config')
8
+ const value = validateLock(lock)
9
+ Object.defineProperty(config, 'revision', { value: value.revision, enumerable: true, configurable: true, writable: false })
10
+ return config
11
+ }
12
+
13
+ /** Data check also covers copies, JSON and configs evaluated in separate module realms. */
14
+ export function assertSchemaLockBound(config: { baseline?: string; revision?: number }): void {
15
+ if (config.baseline === 'workbase-sdk' && (!Number.isSafeInteger(config.revision) || config.revision! < 1)) throw new MigrationDiagnostic({ code: 'schema_lock_not_bound' })
16
+ }
@@ -0,0 +1,3 @@
1
+ /** Shared diagnostic data; safe to import without the build-time loader. */
2
+ export interface SourceLocation { file: string; line: number; column: number }
3
+ export type SourceMap = Record<string, SourceLocation>
@@ -15,7 +15,7 @@ async function migrationRevision(db: D1Database) {
15
15
  // Full validation for health, deployment verification and explicit diagnostic callers.
16
16
  // Ordinary request handling never checks schema compatibility.
17
17
  // SCHEMA_EXPECTED is injected by SST for every deployed Worker. Local workerd/Wrangler uses its own migration ledger.
18
- export async function schemaStatus(env: SchemaEnvironment & { DB: D1Database; AUDIT_KV?: KVNamespace }, config?: Pick<InstanceConfig, 'revision'> & Partial<Pick<InstanceConfig, 'plugins' | 'interactive' | 'entities'>>): Promise<SchemaStatus> {
18
+ export async function schemaStatus(env: SchemaEnvironment & { DB: D1Database; AUDIT_KV?: KVNamespace }, config?: Pick<InstanceConfig, 'revision'> & Partial<Pick<InstanceConfig, 'plugins' | 'interactive' | 'entities' | 'languages'>>): Promise<SchemaStatus> {
19
19
  if (!env.SCHEMA_EXPECTED) return { enabled: false, compatible: !env.STAGE || env.STAGE === 'local', expected: null, applied: null }
20
20
  let expected: SchemaRevision | null = null
21
21
  try {
@@ -28,7 +28,7 @@ export async function schemaStatus(env: SchemaEnvironment & { DB: D1Database; AU
28
28
  if (!config?.plugins || !/^[a-f0-9]{64}$/.test(expected.pluginMigrations ?? '')) throw new Error('missing_plugin_revision')
29
29
  const plugins = resolvePlugins(config.plugins, config.interactive).plugins
30
30
  if (!config.entities) throw new Error('missing_instance_schema')
31
- const pluginStatus = await pluginMigrationStatus(env.DB, plugins, { entities: config.entities })
31
+ const pluginStatus = await pluginMigrationStatus(env.DB, plugins, config as typeof config & Pick<InstanceConfig, 'entities'>)
32
32
  for (const plugin of plugins) await plugin.checkEnvironment?.(env)
33
33
  applied.pluginMigrations = pluginStatus.applied
34
34
  pluginsCompatible = expected.pluginMigrations === pluginStatus.expected && pluginStatus.applied === pluginStatus.expected