@opensaas/stack-cli 0.43.0 → 0.44.0-alpha.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.
- package/README.md +116 -135
- package/dist/.build-hash +1 -0
- package/dist/commands/db.d.ts +23 -0
- package/dist/commands/db.d.ts.map +1 -0
- package/dist/commands/db.js +43 -0
- package/dist/commands/db.js.map +1 -0
- package/dist/commands/dev.d.ts +12 -1
- package/dist/commands/dev.d.ts.map +1 -1
- package/dist/commands/dev.js +519 -22
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/fk-renames.d.ts +14 -0
- package/dist/commands/fk-renames.d.ts.map +1 -0
- package/dist/commands/fk-renames.js +90 -0
- package/dist/commands/fk-renames.js.map +1 -0
- package/dist/commands/generate.d.ts +61 -4
- package/dist/commands/generate.d.ts.map +1 -1
- package/dist/commands/generate.js +225 -138
- package/dist/commands/generate.js.map +1 -1
- package/dist/commands/init.d.ts +6 -0
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +13 -2
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/junction-ids.d.ts +11 -0
- package/dist/commands/junction-ids.d.ts.map +1 -0
- package/dist/commands/junction-ids.js +81 -0
- package/dist/commands/junction-ids.js.map +1 -0
- package/dist/commands/migrate.d.ts +2 -0
- package/dist/commands/migrate.d.ts.map +1 -1
- package/dist/commands/migrate.js +47 -25
- package/dist/commands/migrate.js.map +1 -1
- package/dist/dev/app-runner.d.ts +70 -0
- package/dist/dev/app-runner.d.ts.map +1 -0
- package/dist/dev/app-runner.js +116 -0
- package/dist/dev/app-runner.js.map +1 -0
- package/dist/dev/control.d.ts +73 -0
- package/dist/dev/control.d.ts.map +1 -0
- package/dist/dev/control.js +251 -0
- package/dist/dev/control.js.map +1 -0
- package/dist/dev/staged-reconcile.d.ts +126 -0
- package/dist/dev/staged-reconcile.d.ts.map +1 -0
- package/dist/dev/staged-reconcile.js +289 -0
- package/dist/dev/staged-reconcile.js.map +1 -0
- package/dist/generator/config-load.d.ts +34 -0
- package/dist/generator/config-load.d.ts.map +1 -0
- package/dist/generator/config-load.js +64 -0
- package/dist/generator/config-load.js.map +1 -0
- package/dist/generator/context.d.ts +39 -3
- package/dist/generator/context.d.ts.map +1 -1
- package/dist/generator/context.js +245 -107
- package/dist/generator/context.js.map +1 -1
- package/dist/generator/contract-emit.d.ts +24 -0
- package/dist/generator/contract-emit.d.ts.map +1 -0
- package/dist/generator/contract-emit.js +34 -0
- package/dist/generator/contract-emit.js.map +1 -0
- package/dist/generator/contract-module.d.ts +39 -0
- package/dist/generator/contract-module.d.ts.map +1 -0
- package/dist/generator/contract-module.js +440 -0
- package/dist/generator/contract-module.js.map +1 -0
- package/dist/generator/extension-spaces.d.ts +142 -0
- package/dist/generator/extension-spaces.d.ts.map +1 -0
- package/dist/generator/extension-spaces.js +358 -0
- package/dist/generator/extension-spaces.js.map +1 -0
- package/dist/generator/index.d.ts +12 -4
- package/dist/generator/index.d.ts.map +1 -1
- package/dist/generator/index.js +7 -3
- package/dist/generator/index.js.map +1 -1
- package/dist/generator/lists.d.ts +6 -7
- package/dist/generator/lists.d.ts.map +1 -1
- package/dist/generator/lists.js +33 -13
- package/dist/generator/lists.js.map +1 -1
- package/dist/generator/output-paths.d.ts +62 -19
- package/dist/generator/output-paths.d.ts.map +1 -1
- package/dist/generator/output-paths.js +68 -30
- package/dist/generator/output-paths.js.map +1 -1
- package/dist/generator/prisma-cli.d.ts +61 -0
- package/dist/generator/prisma-cli.d.ts.map +1 -0
- package/dist/generator/prisma-cli.js +92 -0
- package/dist/generator/prisma-cli.js.map +1 -0
- package/dist/generator/prisma-config.d.ts +50 -31
- package/dist/generator/prisma-config.d.ts.map +1 -1
- package/dist/generator/prisma-config.js +72 -65
- package/dist/generator/prisma-config.js.map +1 -1
- package/dist/generator/source-text.d.ts +16 -0
- package/dist/generator/source-text.d.ts.map +1 -0
- package/dist/generator/source-text.js +35 -0
- package/dist/generator/source-text.js.map +1 -0
- package/dist/generator/tables.d.ts +5 -0
- package/dist/generator/tables.d.ts.map +1 -0
- package/dist/generator/tables.js +84 -0
- package/dist/generator/tables.js.map +1 -0
- package/dist/generator/types.d.ts +23 -3
- package/dist/generator/types.d.ts.map +1 -1
- package/dist/generator/types.js +291 -1171
- package/dist/generator/types.js.map +1 -1
- package/dist/index.js +20 -7
- package/dist/index.js.map +1 -1
- package/dist/mcp/lib/documentation-provider.d.ts.map +1 -1
- package/dist/mcp/lib/documentation-provider.js +44 -42
- package/dist/mcp/lib/documentation-provider.js.map +1 -1
- package/dist/mcp/lib/generators/feature-generator.d.ts.map +1 -1
- package/dist/mcp/lib/generators/feature-generator.js +124 -73
- package/dist/mcp/lib/generators/feature-generator.js.map +1 -1
- package/dist/mcp/lib/wizards/migration-wizard.js +6 -6
- package/dist/mcp/lib/wizards/migration-wizard.js.map +1 -1
- package/dist/mcp/lib/wizards/wizard-engine.d.ts.map +1 -1
- package/dist/mcp/lib/wizards/wizard-engine.js +3 -2
- package/dist/mcp/lib/wizards/wizard-engine.js.map +1 -1
- package/dist/mcp/server/stack-mcp-server.js +1 -1
- package/dist/migration/fk-renames.d.ts +39 -0
- package/dist/migration/fk-renames.d.ts.map +1 -0
- package/dist/migration/fk-renames.js +79 -0
- package/dist/migration/fk-renames.js.map +1 -0
- package/dist/migration/generators/migration-generator.d.ts +11 -0
- package/dist/migration/generators/migration-generator.d.ts.map +1 -1
- package/dist/migration/generators/migration-generator.js +83 -150
- package/dist/migration/generators/migration-generator.js.map +1 -1
- package/dist/migration/introspectors/prisma-introspector.d.ts.map +1 -1
- package/dist/migration/introspectors/prisma-introspector.js +1 -0
- package/dist/migration/introspectors/prisma-introspector.js.map +1 -1
- package/dist/migration/junction-ids.d.ts +15 -0
- package/dist/migration/junction-ids.d.ts.map +1 -0
- package/dist/migration/junction-ids.js +58 -0
- package/dist/migration/junction-ids.js.map +1 -0
- package/dist/migration/types.d.ts +2 -0
- package/dist/migration/types.d.ts.map +1 -1
- package/package.json +27 -15
- package/dist/generator/node-build.d.ts +0 -53
- package/dist/generator/node-build.d.ts.map +0 -1
- package/dist/generator/node-build.js +0 -280
- package/dist/generator/node-build.js.map +0 -1
- package/dist/generator/prisma.d.ts +0 -30
- package/dist/generator/prisma.d.ts.map +0 -1
- package/dist/generator/prisma.js +0 -422
- package/dist/generator/prisma.js.map +0 -1
|
@@ -1,53 +1,47 @@
|
|
|
1
1
|
import * as fs from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import { withTsExtension } from './extension.js';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
// Context<TSession>` remains: `Context<TSession>.session` is the caller's own
|
|
9
|
-
// `TSession`, while `StackContext`'s `session` is always the wider `Session |
|
|
10
|
-
// null` (core has no session-generic parameter to narrow it with), so the two
|
|
11
|
-
// are never mutually assignable regardless of `db`. `as` (not `as unknown as`)
|
|
12
|
-
// is enough because `Context<TSession>` is itself assignable to
|
|
13
|
-
// `StackContext<PrismaClient, CustomDB>` (every field it declares — including
|
|
14
|
-
// `TSession` narrowing `Session | null`, and `CustomDB` matching `CustomDB`
|
|
15
|
-
// exactly — is a valid `StackContext` value), which is what TypeScript's `as`
|
|
16
|
-
// requires when the reverse direction doesn't hold.
|
|
17
|
-
export function generateContext(config, configImport) {
|
|
18
|
-
// Defaults to the legacy `../opensaas.config` (bundle one level below the
|
|
19
|
-
// project root); the output-path resolver supplies a recomputed value when
|
|
20
|
-
// the bundle is relocated via the `output` config block. The `.ts`
|
|
21
|
-
// extension keeps the bundle loadable without a consumer `extensionAlias`
|
|
22
|
-
// (see ./extension.ts).
|
|
23
|
-
const configImportPath = withTsExtension(configImport ?? '../opensaas.config');
|
|
24
|
-
const hasCustomConstructor = !!config.db.prismaClientConstructor;
|
|
25
|
-
const hasStorage = !!config.storage && Object.keys(config.storage).length > 0;
|
|
26
|
-
// Prisma 7 requires adapters, so prismaClientConstructor must be provided
|
|
27
|
-
const prismaInstantiation = hasCustomConstructor
|
|
28
|
-
? `resolvedConfig.db.prismaClientConstructor!(PrismaClient)`
|
|
29
|
-
: `(() => {
|
|
30
|
-
throw new Error(
|
|
31
|
-
'Prisma 7 requires a database adapter. Please add prismaClientConstructor to your opensaas.config.ts db configuration.\\n\\n' +
|
|
32
|
-
'Example for SQLite:\\n' +
|
|
33
|
-
'import { PrismaBetterSqlite3 } from \\'@prisma/adapter-better-sqlite3\\'\\n\\n' +
|
|
34
|
-
'db: {\\n' +
|
|
35
|
-
' provider: \\'sqlite\\',\\n' +
|
|
36
|
-
' url: process.env.DATABASE_URL || \\'file:./dev.db\\',\\n' +
|
|
37
|
-
' prismaClientConstructor: (PrismaClient) => {\\n' +
|
|
38
|
-
' const adapter = new PrismaBetterSqlite3({ url: process.env.DATABASE_URL || \\'file:./dev.db\\' })\\n' +
|
|
39
|
-
' return new PrismaClient({ adapter })\\n' +
|
|
40
|
-
' }\\n' +
|
|
41
|
-
'}\\n\\n' +
|
|
42
|
-
'See https://www.prisma.io/docs/orm/overview/databases/database-drivers for more information.'
|
|
43
|
-
)
|
|
44
|
-
})()`;
|
|
45
|
-
const storageUtilities = hasStorage
|
|
46
|
-
? `
|
|
4
|
+
const DEFAULT_REFERENCES = {
|
|
5
|
+
configImport: '../opensaas.config',
|
|
6
|
+
contractJsonImport: '../prisma/contract.json',
|
|
7
|
+
};
|
|
47
8
|
/**
|
|
48
|
-
*
|
|
49
|
-
*
|
|
9
|
+
* The `contract.d.ts` beside a `contract.json`, as a type-only specifier.
|
|
10
|
+
*
|
|
11
|
+
* Spelled `.d.js`, not `.d.ts`: the Contract module (`prisma/contract.ts`)
|
|
12
|
+
* sits in the same directory, and TypeScript resolves `./contract.d.ts` to
|
|
13
|
+
* THAT file, so the import lands on the builder module and `Contract` is not
|
|
14
|
+
* among its exports. `./contract.d.js` takes the standard `.js` -> `.d.ts`
|
|
15
|
+
* mapping and reaches the emitted declarations. The import is type-only and
|
|
16
|
+
* erased, so no loader ever sees the specifier — ADR-0054's `.ts` rule is
|
|
17
|
+
* about value imports.
|
|
50
18
|
*/
|
|
19
|
+
function contractTypesImport(contractJsonImport) {
|
|
20
|
+
return contractJsonImport.replace(/contract\.json$/, 'contract.d.js');
|
|
21
|
+
}
|
|
22
|
+
function storageUtilities(config) {
|
|
23
|
+
const hasStorage = !!config.storage && Object.keys(config.storage).length > 0;
|
|
24
|
+
if (!hasStorage) {
|
|
25
|
+
return `
|
|
26
|
+
const storage = {
|
|
27
|
+
uploadFile: async () => {
|
|
28
|
+
throw new Error('Storage is not configured. Add storage providers to your opensaas.config.ts')
|
|
29
|
+
},
|
|
30
|
+
uploadImage: async () => {
|
|
31
|
+
throw new Error('Storage is not configured. Add storage providers to your opensaas.config.ts')
|
|
32
|
+
},
|
|
33
|
+
deleteFile: async () => {
|
|
34
|
+
throw new Error('Storage is not configured. Add storage providers to your opensaas.config.ts')
|
|
35
|
+
},
|
|
36
|
+
deleteImage: async () => {
|
|
37
|
+
throw new Error('Storage is not configured. Add storage providers to your opensaas.config.ts')
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
`;
|
|
41
|
+
}
|
|
42
|
+
return `
|
|
43
|
+
// Lazily loaded so sharp and the other storage dependencies stay out of a
|
|
44
|
+
// client bundle that only reaches the context for its types.
|
|
51
45
|
let storageRuntime: typeof import('@opensaas/stack-storage/runtime') | null = null
|
|
52
46
|
|
|
53
47
|
async function getStorageRuntime() {
|
|
@@ -63,9 +57,6 @@ async function getStorageRuntime() {
|
|
|
63
57
|
return storageRuntime
|
|
64
58
|
}
|
|
65
59
|
|
|
66
|
-
/**
|
|
67
|
-
* Storage utilities for file/image uploads
|
|
68
|
-
*/
|
|
69
60
|
const storage = {
|
|
70
61
|
uploadFile: async (providerName: string, file: File, buffer: Buffer, options?: unknown) => {
|
|
71
62
|
const config = await getConfig()
|
|
@@ -91,68 +82,179 @@ const storage = {
|
|
|
91
82
|
return runtime.deleteImage(config, metadata as any)
|
|
92
83
|
},
|
|
93
84
|
}
|
|
94
|
-
|
|
95
|
-
|
|
85
|
+
`;
|
|
86
|
+
}
|
|
96
87
|
/**
|
|
97
|
-
*
|
|
88
|
+
* Render `<opensaasDir>/context.ts` — the generated context factory.
|
|
89
|
+
*
|
|
90
|
+
* The client is constructed from the committed `contract.json`, so the runtime
|
|
91
|
+
* executes the same bytes the emitted artifacts were signed over (PRD user
|
|
92
|
+
* story 6), with the stack-owned tripwire in `middleware` and each declared
|
|
93
|
+
* pack's runtime façade in `extensions`. Its connection is
|
|
94
|
+
* `resolveRuntimeConnection`'s: `db.client.pg` when the config supplies a pool
|
|
95
|
+
* factory, otherwise the stack's URL lookup, whose provenance decides the
|
|
96
|
+
* Dev database's single-connection binding (ADR-0049, ADR-0063).
|
|
97
|
+
*
|
|
98
|
+
* The resolved config carries the emitted dependency-set table and
|
|
99
|
+
* unique-constraint map from `tables.ts` on `_tables`, which is how the
|
|
100
|
+
* engine reaches them (ADR-0051, ADR-0042).
|
|
101
|
+
*
|
|
102
|
+
* Known limits:
|
|
103
|
+
* - `Context` is still the bundle's own type; #1136 rewrites `types.ts` to
|
|
104
|
+
* instantiate core's contract-keyed generics, and the client's own typed
|
|
105
|
+
* surface is spec 2's.
|
|
106
|
+
* - Pool lifecycle beyond the module-level singleton — `close()`, the dev
|
|
107
|
+
* loop's ephemeral database, the pooled/direct split — is still unowned. The
|
|
108
|
+
* pool `resolveRuntimeConnection` builds for that database is bound as `pg`,
|
|
109
|
+
* which rc.8 gives no `ownedDispose`, so nothing ends it; it carries a
|
|
110
|
+
* connection timeout instead of relying on one.
|
|
98
111
|
*/
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
deleteImage: async () => {
|
|
110
|
-
throw new Error('Storage is not configured. Add storage providers to your opensaas.config.ts')
|
|
111
|
-
},
|
|
112
|
-
}
|
|
113
|
-
`;
|
|
112
|
+
export function generateContext(config, data, references = {}) {
|
|
113
|
+
const { configImport, contractJsonImport } = { ...DEFAULT_REFERENCES, ...references };
|
|
114
|
+
const configImportPath = withTsExtension(configImport);
|
|
115
|
+
const contractTypesPath = contractTypesImport(contractJsonImport);
|
|
116
|
+
const runtimeExtensionImports = data.extensions
|
|
117
|
+
.map((extension) => `import ${extension.name}Runtime from '${extension.from}/runtime'`)
|
|
118
|
+
.join('\n');
|
|
119
|
+
const runtimeExtensions = data.extensions
|
|
120
|
+
.map((extension) => `${extension.name}Runtime`)
|
|
121
|
+
.join(', ');
|
|
114
122
|
return `/**
|
|
115
123
|
* Auto-generated context factory
|
|
116
124
|
*
|
|
117
|
-
* This module provides a simple API for creating OpenSaas contexts.
|
|
118
|
-
* It abstracts away Prisma client management and configuration.
|
|
119
|
-
*
|
|
120
125
|
* DO NOT EDIT - This file is automatically generated by 'pnpm generate'
|
|
121
126
|
*/
|
|
122
127
|
|
|
123
|
-
import { getContext as getOpensaasContext } from '@opensaas/stack-core'
|
|
128
|
+
import { getContext as getOpensaasContext, requireOrmHandle } from '@opensaas/stack-core'
|
|
129
|
+
import { resolveRuntimeConnection } from '@opensaas/stack-core/client'
|
|
130
|
+
import { originTripwire } from '@opensaas/stack-core/origin'
|
|
131
|
+
import { processGlobal } from '@opensaas/stack-core/internal'
|
|
124
132
|
import type { Session as OpensaasSession, OpenSaasConfig } from '@opensaas/stack-core'
|
|
125
|
-
import
|
|
126
|
-
import
|
|
133
|
+
import postgres from '@prisma/orm-postgres/runtime'
|
|
134
|
+
import { contractFromJson } from '@prisma/orm-postgres/static'
|
|
135
|
+
${runtimeExtensionImports}${runtimeExtensionImports ? '\n' : ''}import type { Contract } from '${contractTypesPath}'
|
|
136
|
+
import contractJson from '${contractJsonImport}' with { type: 'json' }
|
|
137
|
+
import type { Context } from './types.ts'
|
|
138
|
+
import { constraintMap, dependencyTable } from './tables.ts'
|
|
127
139
|
import configOrPromise from '${configImportPath}'
|
|
128
140
|
|
|
129
141
|
// Resolve config if it's a Promise (when plugins are present)
|
|
130
142
|
const configPromise = Promise.resolve(configOrPromise)
|
|
131
143
|
let resolvedConfig: OpenSaasConfig | null = null
|
|
132
144
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
145
|
+
/**
|
|
146
|
+
* The ORM client, built from the committed contract artifact rather than from
|
|
147
|
+
* a generated client tree, so the runtime executes exactly the structure the
|
|
148
|
+
* emitted contract describes.
|
|
149
|
+
*
|
|
150
|
+
* \`resolveRuntimeConnection\` calls \`db.client.pg\` and reads the URL lookup, so
|
|
151
|
+
* this runs once per process, under the singleton below, and never on a config
|
|
152
|
+
* load: nothing that only reads the config opens a connection.
|
|
153
|
+
*/
|
|
154
|
+
function createClient(config: OpenSaasConfig) {
|
|
155
|
+
return postgres({
|
|
156
|
+
contract: contractFromJson<Contract>(contractJson),
|
|
157
|
+
extensions: [${runtimeExtensions}],
|
|
158
|
+
middleware: [originTripwire],
|
|
159
|
+
...resolveRuntimeConnection(config.db.client),
|
|
160
|
+
})
|
|
161
|
+
}
|
|
136
162
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
163
|
+
type RuntimeClient = ReturnType<typeof createClient>
|
|
164
|
+
|
|
165
|
+
interface PublishedClient {
|
|
166
|
+
hash: string
|
|
167
|
+
client: RuntimeClient
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A duck-type check for the value already published under the process-wide
|
|
172
|
+
* registry key, so a foreign value is replaced rather than trusted blindly.
|
|
173
|
+
*/
|
|
174
|
+
function isPublishedClient(value: unknown): value is PublishedClient {
|
|
175
|
+
return (
|
|
176
|
+
typeof value === 'object' &&
|
|
177
|
+
value !== null &&
|
|
178
|
+
'hash' in value &&
|
|
179
|
+
typeof value.hash === 'string' &&
|
|
180
|
+
'client' in value &&
|
|
181
|
+
typeof value.client === 'object' &&
|
|
182
|
+
value.client !== null &&
|
|
183
|
+
'orm' in value.client &&
|
|
184
|
+
'sql' in value.client &&
|
|
185
|
+
'raw' in value.client &&
|
|
186
|
+
'transaction' in value.client
|
|
187
|
+
)
|
|
147
188
|
}
|
|
148
189
|
|
|
190
|
+
const contractHash: string = JSON.stringify([
|
|
191
|
+
contractJson.storage.storageHash,
|
|
192
|
+
contractJson.roots,
|
|
193
|
+
contractJson.domain,
|
|
194
|
+
])
|
|
195
|
+
|
|
196
|
+
let clientPromise: Promise<RuntimeClient> | null = null
|
|
197
|
+
|
|
198
|
+
function getClient() {
|
|
199
|
+
if (clientPromise) return clientPromise
|
|
200
|
+
// Memoised as the promise, not the resolved client: two requests racing the
|
|
201
|
+
// config's own await would otherwise each construct a client, and each call
|
|
202
|
+
// \`db.client.pg\` a second time. The memo is dropped again on failure, so a
|
|
203
|
+
// process that starts before its database does can still reach one — the
|
|
204
|
+
// connection URL is read at construction, not at import.
|
|
205
|
+
//
|
|
206
|
+
// \`processGlobal\` carries the constructed client past this module's own
|
|
207
|
+
// scope, in every environment (ADR-0070). It publishes a holder naming the
|
|
208
|
+
// contract the client was built from: a holder built from another contract
|
|
209
|
+
// is replaced and its pool ended, never adopted, so a hot-reloaded bundle
|
|
210
|
+
// after an additive promote does not run new config over a stale client.
|
|
211
|
+
const attempt = (async () => {
|
|
212
|
+
const config = await getConfig()
|
|
213
|
+
const published = processGlobal('client', isPublishedClient, () => ({
|
|
214
|
+
hash: contractHash,
|
|
215
|
+
client: createClient(config),
|
|
216
|
+
}))
|
|
217
|
+
if (published.hash === contractHash) return published.client
|
|
218
|
+
const stale = published.client
|
|
219
|
+
const replacement = createClient(config)
|
|
220
|
+
published.client = replacement
|
|
221
|
+
published.hash = contractHash
|
|
222
|
+
void Promise.resolve(stale.close()).catch(() => {})
|
|
223
|
+
return replacement
|
|
224
|
+
})().catch((error: unknown) => {
|
|
225
|
+
if (clientPromise === attempt) clientPromise = null
|
|
226
|
+
throw error
|
|
227
|
+
})
|
|
228
|
+
clientPromise = attempt
|
|
229
|
+
return attempt
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The app's config carrying the emitted tables. This is the door the engine
|
|
234
|
+
* reads them through (ADR-0051): it widens a read for a computed field's
|
|
235
|
+
* declared dependencies, and resolves a unique violation to per-field
|
|
236
|
+
* messages, from the generated facts rather than by walking the config.
|
|
237
|
+
*/
|
|
149
238
|
async function getConfig() {
|
|
150
239
|
if (!resolvedConfig) {
|
|
151
|
-
resolvedConfig =
|
|
240
|
+
resolvedConfig = {
|
|
241
|
+
...(await configPromise),
|
|
242
|
+
_tables: { dependencies: dependencyTable, constraints: constraintMap },
|
|
243
|
+
}
|
|
152
244
|
}
|
|
153
245
|
return resolvedConfig
|
|
154
246
|
}
|
|
155
|
-
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The engine reaches a model by list key while a Prisma 8 client exposes its
|
|
250
|
+
* collections at \`db.orm.<namespace>.<Model>\`, so the handle is the reconciled
|
|
251
|
+
* map — the client itself goes in beside it, as the client, which is what
|
|
252
|
+
* \`context.unsafe\` and the transaction every write opens are built over.
|
|
253
|
+
*/
|
|
254
|
+
function ormHandleFor(config: OpenSaasConfig, client: ReturnType<typeof createClient>) {
|
|
255
|
+
return requireOrmHandle(config, client.orm)
|
|
256
|
+
}
|
|
257
|
+
${storageUtilities(config)}
|
|
156
258
|
/**
|
|
157
259
|
* Get OpenSaas context with optional session
|
|
158
260
|
*
|
|
@@ -162,35 +264,71 @@ ${storageUtilities}
|
|
|
162
264
|
* \`\`\`typescript
|
|
163
265
|
* // Anonymous access
|
|
164
266
|
* const context = await getContext()
|
|
165
|
-
* const posts = await context.db.
|
|
267
|
+
* const posts = await context.db.Post.all()
|
|
166
268
|
*
|
|
167
269
|
* // Authenticated access
|
|
168
270
|
* const context = await getContext({ userId: 'user-123' })
|
|
169
|
-
* const myPosts = await context.db.
|
|
170
|
-
*
|
|
171
|
-
* // With custom session type
|
|
172
|
-
* type CustomSession = { userId: string; email: string; role: string } | null
|
|
173
|
-
* const context = await getContext<CustomSession>({ userId: '123', email: 'user@example.com', role: 'admin' })
|
|
174
|
-
* // context.session is now typed as CustomSession
|
|
271
|
+
* const myPosts = await context.db.Post.all()
|
|
175
272
|
* \`\`\`
|
|
176
273
|
*/
|
|
177
274
|
export async function getContext<TSession extends OpensaasSession = OpensaasSession>(session?: TSession): Promise<Context<TSession>> {
|
|
178
275
|
const config = await getConfig()
|
|
179
|
-
const
|
|
180
|
-
return getOpensaasContext
|
|
276
|
+
const db = await getClient()
|
|
277
|
+
return getOpensaasContext(config, ormHandleFor(config, db), session ?? null, storage, false, undefined, undefined, db) as unknown as Context<TSession>
|
|
181
278
|
}
|
|
182
279
|
|
|
280
|
+
async function buildRawContext(): Promise<Context> {
|
|
281
|
+
const config = await getConfig()
|
|
282
|
+
const db = await getClient()
|
|
283
|
+
return getOpensaasContext(config, ormHandleFor(config, db), null, storage, false, undefined, undefined, db) as unknown as Context
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
let rawContextPromise: Promise<Context> | null = null
|
|
287
|
+
|
|
183
288
|
/**
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
289
|
+
* Memoised as the promise, not the resolved context, and dropped again on
|
|
290
|
+
* failure — same reason \`getClient\` drops its own memo. A single \`await\`ed
|
|
291
|
+
* IIFE settles once and stays settled forever, so a process that boots before
|
|
292
|
+
* its database does would otherwise poison \`rawOpensaasContext\` for every
|
|
293
|
+
* later request for the life of the process, even once the database comes up.
|
|
294
|
+
* Nothing here runs at module evaluation: the first attempt starts on the
|
|
295
|
+
* first \`.then()\`/\`.catch()\` a real consumer makes.
|
|
188
296
|
*/
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
297
|
+
function getRawContext(): Promise<Context> {
|
|
298
|
+
if (rawContextPromise) return rawContextPromise
|
|
299
|
+
const attempt = buildRawContext().catch((error: unknown) => {
|
|
300
|
+
if (rawContextPromise === attempt) rawContextPromise = null
|
|
301
|
+
throw error
|
|
302
|
+
})
|
|
303
|
+
rawContextPromise = attempt
|
|
304
|
+
return attempt
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Raw context for module-init-time consumers that can't \`await\` directly
|
|
309
|
+
* (e.g., Better-auth setup). Pass this value itself to helpers like
|
|
310
|
+
* \`createAuth\` that defer real construction behind a lazy Proxy until it
|
|
311
|
+
* resolves - do not await it at module scope.
|
|
312
|
+
*
|
|
313
|
+
* Deliberately not a \`Promise\` instance: it is a stable, \`then\`-able object
|
|
314
|
+
* so a consumer that captures it once — exactly what \`createAuth\` does —
|
|
315
|
+
* keeps retrying construction on every subsequent \`await\` rather than
|
|
316
|
+
* replaying whatever outcome the first attempt happened to settle on. A
|
|
317
|
+
* rejected attempt drops the underlying memo (see \`getRawContext\` above), so
|
|
318
|
+
* a boot that races the database is not fatal for the rest of the process:
|
|
319
|
+
* the next \`await rawOpensaasContext\` tries again instead of replaying the
|
|
320
|
+
* first rejection.
|
|
321
|
+
*/
|
|
322
|
+
export const rawOpensaasContext: Promise<Context> = {
|
|
323
|
+
then: (
|
|
324
|
+
onFulfilled?: ((value: Context) => Context | PromiseLike<Context>) | null,
|
|
325
|
+
onRejected?: ((reason: unknown) => Context | PromiseLike<Context>) | null,
|
|
326
|
+
): Promise<Context> => getRawContext().then(onFulfilled, onRejected),
|
|
327
|
+
catch: (
|
|
328
|
+
onRejected?: ((reason: unknown) => Context | PromiseLike<Context>) | null,
|
|
329
|
+
): Promise<Context> => getRawContext().catch(onRejected),
|
|
330
|
+
finally: (onFinally?: (() => void) | null): Promise<Context> => getRawContext().finally(onFinally),
|
|
331
|
+
} as unknown as Promise<Context>
|
|
194
332
|
|
|
195
333
|
/**
|
|
196
334
|
* Re-export resolved config for use in admin pages and server actions
|
|
@@ -199,8 +337,8 @@ export const rawOpensaasContext = (async () => {
|
|
|
199
337
|
export const config = getConfig()
|
|
200
338
|
`;
|
|
201
339
|
}
|
|
202
|
-
export function writeContext(config, outputPath,
|
|
203
|
-
const content = generateContext(config,
|
|
340
|
+
export function writeContext(config, data, outputPath, references) {
|
|
341
|
+
const content = generateContext(config, data, references);
|
|
204
342
|
const dir = path.dirname(outputPath);
|
|
205
343
|
if (!fs.existsSync(dir)) {
|
|
206
344
|
fs.mkdirSync(dir, { recursive: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/generator/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AACxB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/generator/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AACxB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAchD,MAAM,kBAAkB,GAAsB;IAC5C,YAAY,EAAE,oBAAoB;IAClC,kBAAkB,EAAE,yBAAyB;CAC9C,CAAA;AAED;;;;;;;;;;GAUG;AACH,SAAS,mBAAmB,CAAC,kBAA0B;IACrD,OAAO,kBAAkB,CAAC,OAAO,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAAA;AACvE,CAAC;AAED,SAAS,gBAAgB,CAAC,MAAsB;IAC9C,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAA;IAC7E,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO;;;;;;;;;;;;;;;CAeV,CAAA;IACC,CAAC;IAED,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CR,CAAA;AACD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,eAAe,CAC7B,MAAsB,EACtB,IAAkB,EAClB,UAAU,GAA+B,EAAE;IAE3C,MAAM,EAAE,YAAY,EAAE,kBAAkB,EAAE,GAAG,EAAE,GAAG,kBAAkB,EAAE,GAAG,UAAU,EAAE,CAAA;IACrF,MAAM,gBAAgB,GAAG,eAAe,CAAC,YAAY,CAAC,CAAA;IACtD,MAAM,iBAAiB,GAAG,mBAAmB,CAAC,kBAAkB,CAAC,CAAA;IAEjE,MAAM,uBAAuB,GAAG,IAAI,CAAC,UAAU;SAC5C,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,UAAU,SAAS,CAAC,IAAI,iBAAiB,SAAS,CAAC,IAAI,WAAW,CAAC;SACtF,IAAI,CAAC,IAAI,CAAC,CAAA;IACb,MAAM,iBAAiB,GAAG,IAAI,CAAC,UAAU;SACtC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,GAAG,SAAS,CAAC,IAAI,SAAS,CAAC;SAC9C,IAAI,CAAC,IAAI,CAAC,CAAA;IAEb,OAAO;;;;;;;;;;;;;EAaP,uBAAuB,GAAG,uBAAuB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,kCAAkC,iBAAiB;4BACtF,kBAAkB;;;+BAGf,gBAAgB;;;;;;;;;;;;;;;;;;mBAkB5B,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoGlC,gBAAgB,CAAC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiFzB,CAAA;AACD,CAAC;AAED,MAAM,UAAU,YAAY,CAC1B,MAAsB,EACtB,IAAkB,EAClB,UAAkB,EAClB,UAAuC;IAEvC,MAAM,OAAO,GAAG,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IAEzD,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;IACpC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACxB,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IACxC,CAAC;IAED,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;AAChD,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Thrown when `prisma contract emit` exits non-zero. */
|
|
2
|
+
export declare class ContractEmitError extends Error {
|
|
3
|
+
/** The CLI's combined stdout and stderr, verbatim. */
|
|
4
|
+
readonly output: string;
|
|
5
|
+
readonly exitCode: number | null;
|
|
6
|
+
constructor(
|
|
7
|
+
/** The CLI's combined stdout and stderr, verbatim. */
|
|
8
|
+
output: string, exitCode: number | null);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Shell to `prisma contract emit`, which reads `prisma.config.ts`, evaluates
|
|
12
|
+
* the Contract module and writes `contract.json` + `contract.d.ts` into
|
|
13
|
+
* `outputPath`.
|
|
14
|
+
*
|
|
15
|
+
* @param configPath - A Prisma config to read instead of the project root's,
|
|
16
|
+
* which is how a staged Contract module is emitted without the live one
|
|
17
|
+
* being touched.
|
|
18
|
+
*
|
|
19
|
+
* @throws {ContractEmitError} on a non-zero exit, carrying the CLI's own
|
|
20
|
+
* output so a purity violation or a validation failure reaches the user as
|
|
21
|
+
* the toolchain worded it.
|
|
22
|
+
*/
|
|
23
|
+
export declare function emitContract(cwd: string, outputPath: string, configPath?: string): Promise<void>;
|
|
24
|
+
//# sourceMappingURL=contract-emit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-emit.d.ts","sourceRoot":"","sources":["../../src/generator/contract-emit.ts"],"names":[],"mappings":"AAEA,yDAAyD;AACzD,qBAAa,iBAAkB,SAAQ,KAAK;IAExC,sDAAsD;IACtD,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAHlC;IACE,sDAAsD;IAC7C,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GAAG,IAAI,EAMjC;CACF;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,EAClB,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,IAAI,CAAC,CAIf"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { runPrismaCli } from './prisma-cli.js';
|
|
2
|
+
/** Thrown when `prisma contract emit` exits non-zero. */
|
|
3
|
+
export class ContractEmitError extends Error {
|
|
4
|
+
output;
|
|
5
|
+
exitCode;
|
|
6
|
+
constructor(
|
|
7
|
+
/** The CLI's combined stdout and stderr, verbatim. */
|
|
8
|
+
output, exitCode) {
|
|
9
|
+
super(`prisma contract emit failed (exit ${exitCode ?? 'signal'}).\n\n${output.trim()}`.trimEnd());
|
|
10
|
+
this.output = output;
|
|
11
|
+
this.exitCode = exitCode;
|
|
12
|
+
this.name = 'ContractEmitError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Shell to `prisma contract emit`, which reads `prisma.config.ts`, evaluates
|
|
17
|
+
* the Contract module and writes `contract.json` + `contract.d.ts` into
|
|
18
|
+
* `outputPath`.
|
|
19
|
+
*
|
|
20
|
+
* @param configPath - A Prisma config to read instead of the project root's,
|
|
21
|
+
* which is how a staged Contract module is emitted without the live one
|
|
22
|
+
* being touched.
|
|
23
|
+
*
|
|
24
|
+
* @throws {ContractEmitError} on a non-zero exit, carrying the CLI's own
|
|
25
|
+
* output so a purity violation or a validation failure reaches the user as
|
|
26
|
+
* the toolchain worded it.
|
|
27
|
+
*/
|
|
28
|
+
export async function emitContract(cwd, outputPath, configPath) {
|
|
29
|
+
const config = configPath === undefined ? [] : ['--config', configPath];
|
|
30
|
+
const run = await runPrismaCli(cwd, ['contract', 'emit', ...config, '--output-path', outputPath]);
|
|
31
|
+
if (run.exitCode !== 0)
|
|
32
|
+
throw new ContractEmitError(run.output, run.exitCode);
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=contract-emit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-emit.js","sourceRoot":"","sources":["../../src/generator/contract-emit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAE9C,yDAAyD;AACzD,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAG/B,MAAM;IACN,QAAQ;IAHnB;IACE,sDAAsD;IAC7C,MAAc,EACd,QAAuB;QAEhC,KAAK,CACH,qCAAqC,QAAQ,IAAI,QAAQ,SAAS,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,CAC5F,CAAA;sBALQ,MAAM;wBACN,QAAQ;QAKjB,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAA;IACjC,CAAC;CACF;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,GAAW,EACX,UAAkB,EAClB,UAAmB;IAEnB,MAAM,MAAM,GAAG,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;IACvE,MAAM,GAAG,GAAG,MAAM,YAAY,CAAC,GAAG,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,eAAe,EAAE,UAAU,CAAC,CAAC,CAAA;IACjG,IAAI,GAAG,CAAC,QAAQ,KAAK,CAAC;QAAE,MAAM,IAAI,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAA;AAC/E,CAAC"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ContractData } from '@opensaas/stack-core';
|
|
2
|
+
/**
|
|
3
|
+
* Render the standalone Contract module — `prisma/contract.ts` — from core's
|
|
4
|
+
* derivation (ADR-0040, ADR-0057).
|
|
5
|
+
*
|
|
6
|
+
* The module imports only from `@prisma/orm-postgres/contract-builder`,
|
|
7
|
+
* `@prisma/orm-postgres/adapter/column-types` and each declared extension
|
|
8
|
+
* pack's `/pack` subpath. It imports nothing from `opensaas.config.ts`, reads
|
|
9
|
+
* no environment variable and contains no non-literal expression, so it
|
|
10
|
+
* satisfies Prisma's purity rules by construction and `prisma contract emit`
|
|
11
|
+
* can evaluate it on its own.
|
|
12
|
+
*
|
|
13
|
+
* Every builder call is the one {@link buildPrismaContract} makes for the same
|
|
14
|
+
* data, so the rendered module and the in-process derivation emit identical
|
|
15
|
+
* contract JSON — the equivalence test that keeps the two from drifting.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* import { deriveContract } from '@opensaas/stack-core'
|
|
20
|
+
* fs.writeFileSync('prisma/contract.ts', renderContractModule(deriveContract(config)))
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* Known limits:
|
|
24
|
+
* - A model or enum name must be a valid TypeScript identifier: each becomes a
|
|
25
|
+
* `const` declaration (`model_<Name>` / `enum_<Name>`), and this renderer
|
|
26
|
+
* does not re-check the name. Relation, column and index names have no such
|
|
27
|
+
* limit — they are rendered through `key()`/`member()`, which quote whatever
|
|
28
|
+
* is not an identifier.
|
|
29
|
+
* - The emitted relation targets are thunks (`() => Target`), so a model may
|
|
30
|
+
* reference one declared later, but every target must be a model in the
|
|
31
|
+
* same contract — cross-space references are not rendered.
|
|
32
|
+
* - An extension pack's type constructor is emitted as
|
|
33
|
+
* `type.<pack>.<type>(...)` with the descriptor's literal arguments; the
|
|
34
|
+
* renderer does not know the pack's constructor list, so a misspelled type
|
|
35
|
+
* surfaces at `contract emit` rather than here.
|
|
36
|
+
*/
|
|
37
|
+
export declare function renderContractModule(data: ContractData): string;
|
|
38
|
+
export declare function writeContractModule(data: ContractData, outputPath: string): void;
|
|
39
|
+
//# sourceMappingURL=contract-module.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-module.d.ts","sourceRoot":"","sources":["../../src/generator/contract-module.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEV,YAAY,EAIb,MAAM,sBAAsB,CAAA;AAkW7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,MAAM,CAsF/D;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAShF"}
|