@aventara/prisma7-adapter 1.0.0-rc.0 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +552 -0
  2. package/README.md +407 -329
  3. package/dist/discovery/artifact.loader.d.ts +10 -6
  4. package/dist/discovery/artifact.loader.js +20 -20
  5. package/dist/discovery/capability-surface.interface.d.ts +1 -1
  6. package/dist/discovery/capability.deriver.d.ts +9 -6
  7. package/dist/discovery/capability.deriver.js +41 -6
  8. package/dist/discovery/client-shape.verifier.d.ts +1 -1
  9. package/dist/discovery/client-shape.verifier.js +2 -2
  10. package/dist/discovery/discovery-artifact.interface.d.ts +38 -47
  11. package/dist/discovery/discovery-artifact.interface.js +1 -1
  12. package/dist/discovery/enum.mapper.d.ts +2 -2
  13. package/dist/discovery/field.mapper.d.ts +13 -13
  14. package/dist/discovery/field.mapper.js +10 -10
  15. package/dist/discovery/identifier.mapper.d.ts +7 -7
  16. package/dist/discovery/installed-client.locator.d.ts +13 -0
  17. package/dist/discovery/installed-client.locator.js +43 -0
  18. package/dist/discovery/model.discoverer.d.ts +7 -4
  19. package/dist/discovery/model.discoverer.js +61 -19
  20. package/dist/discovery/operations.deriver.d.ts +6 -6
  21. package/dist/discovery/schema-facts.interface.d.ts +3 -3
  22. package/dist/discovery/schema.reader.d.ts +2 -2
  23. package/dist/discovery/schema.reader.js +5 -5
  24. package/dist/discovery/types.reader.d.ts +2 -2
  25. package/dist/discovery/types.reader.js +22 -22
  26. package/dist/discovery/vocabulary.dictionary.d.ts +14 -14
  27. package/dist/discovery/vocabulary.dictionary.js +1 -1
  28. package/dist/errors/back-reference.locator.d.ts +25 -0
  29. package/dist/errors/back-reference.locator.js +100 -0
  30. package/dist/errors/bigint-binding.locator.d.ts +7 -0
  31. package/dist/errors/bigint-binding.locator.js +27 -0
  32. package/dist/errors/error.normalizer.d.ts +44 -6
  33. package/dist/errors/error.normalizer.js +96 -7
  34. package/dist/errors/prisma-error.reader.d.ts +6 -0
  35. package/dist/errors/prisma-error.reader.js +3 -0
  36. package/dist/execution/first-variant.emulator.d.ts +4 -4
  37. package/dist/execution/first-variant.emulator.js +13 -9
  38. package/dist/execution/operation.executor.d.ts +15 -9
  39. package/dist/execution/operation.executor.js +34 -17
  40. package/dist/execution/result.shaper.d.ts +3 -3
  41. package/dist/execution/result.shaper.js +7 -7
  42. package/dist/execution/sql-statement.executor.d.ts +9 -0
  43. package/dist/execution/sql-statement.executor.js +58 -0
  44. package/dist/execution/transaction.executor.d.ts +12 -8
  45. package/dist/execution/transaction.executor.js +11 -5
  46. package/dist/generate/artifact.emitter.d.ts +11 -7
  47. package/dist/generate/artifact.emitter.js +60 -18
  48. package/dist/generate/computed-fields.reader.d.ts +19 -0
  49. package/dist/generate/computed-fields.reader.js +210 -0
  50. package/dist/generate/declared-support.reader.d.ts +1 -1
  51. package/dist/generate/discovery.cli.d.ts +4 -3
  52. package/dist/generate/discovery.cli.js +31 -15
  53. package/dist/generate/existence.gate.d.ts +4 -4
  54. package/dist/generate/existence.gate.js +4 -4
  55. package/dist/generate/index.d.ts +13 -5
  56. package/dist/generate/index.js +5 -2
  57. package/dist/generate/prisma.generate.d.ts +24 -8
  58. package/dist/generate/prisma.generate.js +52 -15
  59. package/dist/index.d.ts +4 -4
  60. package/dist/prisma-client.interface.d.ts +22 -8
  61. package/dist/prisma-client.interface.js +7 -0
  62. package/dist/prisma.adapter.d.ts +16 -16
  63. package/dist/prisma.adapter.js +48 -5
  64. package/dist/provider/provider-profile.d.ts +29 -13
  65. package/dist/provider/provider-profile.js +21 -0
  66. package/dist/translation/json-null.sentinel.d.ts +7 -0
  67. package/dist/translation/json-null.sentinel.js +17 -0
  68. package/dist/translation/mutation.translator.d.ts +8 -8
  69. package/dist/translation/mutation.translator.js +37 -30
  70. package/dist/translation/operation.translator.d.ts +7 -7
  71. package/dist/translation/operation.translator.js +12 -12
  72. package/dist/translation/order-pagination.translator.d.ts +5 -5
  73. package/dist/translation/order-pagination.translator.js +16 -16
  74. package/dist/translation/projection.translator.d.ts +4 -4
  75. package/dist/translation/projection.translator.js +11 -11
  76. package/dist/translation/scalar.conversion.d.ts +9 -9
  77. package/dist/translation/scalar.conversion.js +11 -11
  78. package/dist/translation/where.translator.d.ts +5 -5
  79. package/dist/translation/where.translator.js +114 -31
  80. package/package.json +6 -6
@@ -5,7 +5,7 @@ const USAGE = `aventara-prisma7-generate — emit a @aventara/prisma7-adapter di
5
5
 
6
6
  Usage:
7
7
  aventara-prisma7-generate --schema <path> --client <dir> --provider <name> \\
8
- --driver <name> --out <file>
8
+ --driver <name> --out <file> [--config <file>]
9
9
 
10
10
  Options:
11
11
  --schema <path> The schema.prisma file, or a Prisma 7 schema folder.
@@ -13,10 +13,16 @@ Options:
13
13
  --provider <name> ${PRISMA_PROVIDERS.join(" | ")}
14
14
  --driver <name> ${PRISMA_DRIVERS.join(" | ")}
15
15
  --out <file> Where to write the emitted artifact module (a .ts file).
16
+ --config <file> Optional: your Aventara configuration module, such as
17
+ src/aventara.config.ts (its \`aventaraConfig\` export, or
18
+ its default). The artifact states which fields it
19
+ computes, so the stages that run before compute may leave
20
+ exactly those out of a create.
16
21
  -h, --help Print this and exit 0.
17
22
 
18
- The artifact must NOT be written inside --client: the types reader reads every
19
- .ts file under that root and refuses one that is not generated-client output.
23
+ The artifact must NOT be written inside --client: the next \`prisma generate\`
24
+ clears that directory and would delete it. Such an --out is refused, and so is
25
+ an --out that names a directory.
20
26
 
21
27
  Requires a Prisma 7 CLI and \`typescript\` to be resolvable from your project.
22
28
  Both are optional peer dependencies of this package, so neither is installed on
@@ -25,8 +31,8 @@ is \`@prisma/prisma7\` (bin \`prisma7\`) when it is installed, else \`prisma\`
25
31
  when its version is in this package's declared range; TypeScript 7, which has
26
32
  no classic compiler API, is refused.`;
27
33
  const PROVIDERS = PRISMA_PROVIDERS;
28
- class PrismaGenerateCliError extends Error {
29
- name = "PrismaGenerateCliError";
34
+ class AvPrismaGenerateCliError extends Error {
35
+ name = "AvPrismaGenerateCliError";
30
36
  }
31
37
  const FLAGS = {
32
38
  "--schema": "schema",
@@ -34,36 +40,38 @@ const FLAGS = {
34
40
  "--provider": "provider",
35
41
  "--driver": "driver",
36
42
  "--out": "artifactFile",
43
+ "--config": "config",
37
44
  };
45
+ const OPTIONAL = ["config"];
38
46
  export function parsePrismaGenerateArguments(argv) {
39
47
  const seen = {};
40
48
  for (let index = 0; index < argv.length; index += 1) {
41
49
  const flag = argv[index];
42
50
  const member = FLAGS[flag];
43
51
  if (member === undefined) {
44
- throw new PrismaGenerateCliError(`unknown argument \`${flag}\`.\n\n${USAGE}`);
52
+ throw new AvPrismaGenerateCliError(`unknown argument \`${flag}\`.\n\n${USAGE}`);
45
53
  }
46
54
  const value = argv[index + 1];
47
55
  if (value === undefined || value.startsWith("--")) {
48
- throw new PrismaGenerateCliError(`\`${flag}\` takes a value.\n\n${USAGE}`);
56
+ throw new AvPrismaGenerateCliError(`\`${flag}\` takes a value.\n\n${USAGE}`);
49
57
  }
50
58
  seen[member] = value;
51
59
  index += 1;
52
60
  }
53
- const missing = Object.values(FLAGS).filter((member) => seen[member] === undefined);
61
+ const missing = Object.values(FLAGS).filter((member) => seen[member] === undefined && !OPTIONAL.includes(member));
54
62
  if (missing.length > 0) {
55
- throw new PrismaGenerateCliError(`missing required argument(s): ${missing
63
+ throw new AvPrismaGenerateCliError(`missing required argument(s): ${missing
56
64
  .map((member) => Object.entries(FLAGS).find(([, name]) => name === member)?.[0] ??
57
65
  member)
58
66
  .join(", ")}.\n\n${USAGE}`);
59
67
  }
60
68
  const provider = seen.provider;
61
69
  if (!PROVIDERS.includes(provider)) {
62
- throw new PrismaGenerateCliError(`\`--provider ${seen.provider}\` is not one of ${PROVIDERS.join(", ")}.`);
70
+ throw new AvPrismaGenerateCliError(`\`--provider ${seen.provider}\` is not one of ${PROVIDERS.join(", ")}.`);
63
71
  }
64
72
  const driver = seen.driver;
65
73
  if (!PRISMA_DRIVERS.includes(driver)) {
66
- throw new PrismaGenerateCliError(`\`--driver ${seen.driver}\` is not one of ${PRISMA_DRIVERS.join(", ")}.`);
74
+ throw new AvPrismaGenerateCliError(`\`--driver ${seen.driver}\` is not one of ${PRISMA_DRIVERS.join(", ")}.`);
67
75
  }
68
76
  return {
69
77
  schema: path.resolve(seen.schema),
@@ -71,6 +79,7 @@ export function parsePrismaGenerateArguments(argv) {
71
79
  provider,
72
80
  driver,
73
81
  artifactFile: path.resolve(seen.artifactFile),
82
+ ...(seen.config === undefined ? {} : { config: path.resolve(seen.config) }),
74
83
  };
75
84
  }
76
85
  async function main(argv) {
@@ -85,6 +94,12 @@ async function main(argv) {
85
94
  for (const absence of result.excluded) {
86
95
  process.stdout.write(`excluded: ${absence.message}\n`);
87
96
  }
97
+ if (result.computedFields?.kind === "read") {
98
+ process.stdout.write(`computed fields: read from ${options.config ?? "the configuration"}\n`);
99
+ }
100
+ else if (result.computedFields?.kind === "unread") {
101
+ process.stdout.write(`computed fields: not read, ${result.computedFields.reason}; the stages before compute may leave any create field out. Write the configuration \`as const\` there.\n`);
102
+ }
88
103
  for (const exemption of result.exemptions) {
89
104
  process.stdout.write(`exempt (${exemption.kind}) ${exemption.entity}: ${exemption.reason}\n`);
90
105
  }
@@ -95,11 +110,12 @@ export async function runFromProcess() {
95
110
  process.exitCode = await main(process.argv.slice(2));
96
111
  }
97
112
  catch (error) {
98
- const named = error instanceof PrismaGenerateCliError ||
113
+ const named = error instanceof AvPrismaGenerateCliError ||
99
114
  (error instanceof Error &&
100
- (error.name === "PrismaGenerateStepError" ||
101
- error.name === "PrismaModelCompositionError" ||
102
- error.name === "PrismaSchemaReaderError"));
115
+ (error.name === "AvPrismaGenerateStepError" ||
116
+ error.name === "AvPrismaModelCompositionError" ||
117
+ error.name === "AvPrismaConfigReaderError" ||
118
+ error.name === "AvPrismaSchemaReaderError"));
103
119
  process.stderr.write(named
104
120
  ? `aventara-prisma7-generate: ${error.message}\n`
105
121
  : `${String(error instanceof Error ? error.stack : error)}\n`);
@@ -14,19 +14,19 @@ export type PrismaEntityAbsence = {
14
14
  readonly message: string;
15
15
  };
16
16
  export type PrismaExistenceGateResult = {
17
- /** Resource names admitted into the `AdapterModel`, in PSL declaration order. */
17
+ /** Resource names admitted into the `AvAdapterModel`, in PSL declaration order. */
18
18
  readonly admitted: readonly string[];
19
19
  /** Absences PSL itself explains. Reported; never fatal. */
20
20
  readonly excluded: readonly PrismaEntityAbsence[];
21
21
  };
22
- export declare class PrismaExistenceGateError extends Error {
23
- readonly name = "PrismaExistenceGateError";
22
+ export declare class AvPrismaExistenceGateError extends Error {
23
+ readonly name = "AvPrismaExistenceGateError";
24
24
  readonly absences: readonly PrismaEntityAbsence[];
25
25
  constructor(absences: readonly PrismaEntityAbsence[]);
26
26
  }
27
27
  /**
28
28
  * Runs the gate. Returns what was admitted and what PSL explained away; throws
29
- * {@link PrismaExistenceGateError} listing every unexplained absence at once,
29
+ * {@link AvPrismaExistenceGateError} listing every unexplained absence at once,
30
30
  * because fixing them one build at a time is how a schema migration becomes a
31
31
  * week.
32
32
  */
@@ -1,5 +1,5 @@
1
- export class PrismaExistenceGateError extends Error {
2
- name = "PrismaExistenceGateError";
1
+ export class AvPrismaExistenceGateError extends Error {
2
+ name = "AvPrismaExistenceGateError";
3
3
  absences;
4
4
  constructor(absences) {
5
5
  super([
@@ -19,7 +19,7 @@ function surfaceSays(entity, kind) {
19
19
  : `the generated surface for \`${entity.split(".")[0]}\` does not expose it`;
20
20
  }
21
21
  function explainedMessage(entity, kind, explanation, site) {
22
- return `\`${entity}\` is declared at ${where(site)} and ${surfaceSays(entity, kind)}, because the schema marks it \`${explanation}\`. It is excluded from the AdapterModel, which an entity enters only where the generated types expose it.`;
22
+ return `\`${entity}\` is declared at ${where(site)} and ${surfaceSays(entity, kind)}, because the schema marks it \`${explanation}\`. It is excluded from the AvAdapterModel, which an entity enters only where the generated types expose it.`;
23
23
  }
24
24
  function unexplainedMessage(entity, kind, site) {
25
25
  const instruction = kind === "model" ? "`@@ignore`" : "`@ignore`";
@@ -79,7 +79,7 @@ export function applyExistenceGate(facts, surface) {
79
79
  }
80
80
  }
81
81
  if (unexplained.length > 0) {
82
- throw new PrismaExistenceGateError(unexplained);
82
+ throw new AvPrismaExistenceGateError(unexplained);
83
83
  }
84
84
  return { admitted, excluded: explained };
85
85
  }
@@ -1,9 +1,11 @@
1
- import type { PrismaDriver, PrismaProvider } from "../provider/provider-profile.js";
1
+ import type { AvPrismaDriver, AvPrismaProvider } from "../provider/provider-profile.js";
2
2
  import type { PrismaGenerateResult, PrismaGenerateToolchain } from "./prisma.generate.js";
3
- export { createPrismaModelComposer, PrismaModelCompositionError, } from "../discovery/model.discoverer.js";
3
+ export { AvPrismaModelCompositionError, createPrismaModelComposer, } from "../discovery/model.discoverer.js";
4
+ export type { ConfigComputedFieldsReading } from "./computed-fields.reader.js";
5
+ export { AvPrismaConfigReaderError, readConfigComputedFields, } from "./computed-fields.reader.js";
4
6
  export type { PrismaEntityAbsence } from "./existence.gate.js";
5
7
  export type { PrismaComposedArtifact, PrismaGenerateRequest, PrismaGenerateResult, PrismaGenerateToolchain, PrismaModelComposer, } from "./prisma.generate.js";
6
- export { createPrismaGenerateToolchain, PINNED_PRISMA_MAJOR, PrismaGenerateStepError, runPrismaGenerateStep, } from "./prisma.generate.js";
8
+ export { AvPrismaGenerateStepError, createPrismaGenerateToolchain, PINNED_PRISMA_MAJOR, runPrismaGenerateStep, } from "./prisma.generate.js";
7
9
  export type { PrismaReaderExemption } from "./reader-crosscheck.js";
8
10
  /** One engine's generate request, as a consumer states it. */
9
11
  export type PrismaDiscoveryGenerateRequest = {
@@ -11,11 +13,17 @@ export type PrismaDiscoveryGenerateRequest = {
11
13
  readonly schema: string;
12
14
  /** The generator's `output` directory: the generated client's root. */
13
15
  readonly clientDirectory: string;
14
- readonly provider: PrismaProvider;
16
+ readonly provider: AvPrismaProvider;
15
17
  /** The driver the application will pass to `createPrismaAdapter`. */
16
- readonly driver: PrismaDriver;
18
+ readonly driver: AvPrismaDriver;
17
19
  /** Where the emitted TypeScript artifact module is written. */
18
20
  readonly artifactFile: string;
21
+ /**
22
+ * The Aventara configuration module whose computed fields the artifact
23
+ * states (`src/aventara.config.ts` in a scaffolded project); left out, it
24
+ * states none.
25
+ */
26
+ readonly config?: string;
19
27
  /** Replaces the step's external effects; omit it to use the installed Prisma and TypeScript. */
20
28
  readonly toolchain?: PrismaGenerateToolchain;
21
29
  };
@@ -1,8 +1,9 @@
1
1
  import { createPrismaModelComposer } from "../discovery/model.discoverer.js";
2
2
  import { resolveProviderProfile } from "../provider/provider-profile.js";
3
3
  import { runPrismaGenerateStep } from "./prisma.generate.js";
4
- export { createPrismaModelComposer, PrismaModelCompositionError, } from "../discovery/model.discoverer.js";
5
- export { createPrismaGenerateToolchain, PINNED_PRISMA_MAJOR, PrismaGenerateStepError, runPrismaGenerateStep, } from "./prisma.generate.js";
4
+ export { AvPrismaModelCompositionError, createPrismaModelComposer, } from "../discovery/model.discoverer.js";
5
+ export { AvPrismaConfigReaderError, readConfigComputedFields, } from "./computed-fields.reader.js";
6
+ export { AvPrismaGenerateStepError, createPrismaGenerateToolchain, PINNED_PRISMA_MAJOR, runPrismaGenerateStep, } from "./prisma.generate.js";
6
7
  export async function generatePrismaDiscoveryArtifact(request) {
7
8
  const profile = resolveProviderProfile({
8
9
  provider: request.provider,
@@ -13,8 +14,10 @@ export async function generatePrismaDiscoveryArtifact(request) {
13
14
  clientDirectory: request.clientDirectory,
14
15
  provider: request.provider,
15
16
  artifactFile: request.artifactFile,
17
+ ...(request.config === undefined ? {} : { config: request.config }),
16
18
  composeModel: createPrismaModelComposer({
17
19
  transactions: profile.transactions,
20
+ filterModes: profile.filterModes,
18
21
  }),
19
22
  ...(request.toolchain === undefined
20
23
  ? {}
@@ -1,25 +1,25 @@
1
1
  import type { PrismaCapabilitySurface } from "../discovery/capability-surface.interface.js";
2
- import type { PrismaAdapterModel, PrismaCreateRequirementTable, PrismaReferentialActionTable, PrismaTranslationTable } from "../discovery/discovery-artifact.interface.js";
2
+ import type { AvPrismaAdapterModel, AvPrismaReferentialActionTable, PrismaTranslationTable } from "../discovery/discovery-artifact.interface.js";
3
3
  import type { PrismaSchemaFacts } from "../discovery/schema-facts.interface.js";
4
- import type { PrismaProvider } from "../provider/provider-profile.js";
4
+ import type { AvPrismaProvider } from "../provider/provider-profile.js";
5
+ import { type ConfigComputedFieldsReading } from "./computed-fields.reader.js";
5
6
  import type { PrismaEntityAbsence } from "./existence.gate.js";
6
7
  import { type PrismaCli } from "./prisma-cli.resolver.js";
7
8
  import type { PrismaReaderExemption } from "./reader-crosscheck.js";
8
9
  /** The Prisma major this package generates for. */
9
10
  export declare const PINNED_PRISMA_MAJOR = 7;
10
11
  /** Thrown when the generate step refuses; the message says why and what to change. */
11
- export declare class PrismaGenerateStepError extends Error {
12
- readonly name = "PrismaGenerateStepError";
12
+ export declare class AvPrismaGenerateStepError extends Error {
13
+ readonly name = "AvPrismaGenerateStepError";
13
14
  }
14
15
  /**
15
16
  * What composition produces: the model, Prisma addressing, referential actions
16
17
  * and create requirements the artifact carries.
17
18
  */
18
19
  export type PrismaComposedArtifact = {
19
- readonly model: PrismaAdapterModel;
20
+ readonly model: AvPrismaAdapterModel;
20
21
  readonly translation: PrismaTranslationTable;
21
- readonly referentialActions: PrismaReferentialActionTable;
22
- readonly createRequirements: PrismaCreateRequirementTable;
22
+ readonly referentialActions: AvPrismaReferentialActionTable;
23
23
  };
24
24
  /** Composes the schema's and the generated client's facts into the artifact's contents. */
25
25
  export type PrismaModelComposer = (input: {
@@ -38,16 +38,27 @@ export type PrismaGenerateToolchain = {
38
38
  readonly readSchema: (location: string) => Promise<PrismaSchemaFacts>;
39
39
  readonly readSurface: (clientDirectory: string) => PrismaCapabilitySurface;
40
40
  readonly writeArtifact: (file: string, source: string) => Promise<void>;
41
+ /**
42
+ * Reads which fields a configuration computes off its type. Optional: the
43
+ * TypeScript reader is used when it is left out.
44
+ */
45
+ readonly readComputedFields?: (configFile: string) => ConfigComputedFieldsReading;
41
46
  };
42
47
  /** What {@link runPrismaGenerateStep} needs. */
43
48
  export type PrismaGenerateRequest = {
44
49
  /** The `schema.prisma` file, or a Prisma 7 schema folder. */
45
50
  readonly schema: string;
46
51
  readonly clientDirectory: string;
47
- readonly provider: PrismaProvider;
52
+ readonly provider: AvPrismaProvider;
48
53
  /** Where the emitted TypeScript artifact module is written. */
49
54
  readonly artifactFile: string;
50
55
  readonly composeModel: PrismaModelComposer;
56
+ /**
57
+ * The application's Aventara configuration module (`src/aventara.config.ts`
58
+ * in a scaffolded project), whose computed fields the artifact states. Left
59
+ * out, the artifact states none (`computedFields: null`).
60
+ */
61
+ readonly config?: string;
51
62
  readonly toolchain?: PrismaGenerateToolchain;
52
63
  };
53
64
  /** What {@link runPrismaGenerateStep} produced. */
@@ -60,6 +71,11 @@ export type PrismaGenerateResult = {
60
71
  /** PSL-only entities the schema itself explained away. */
61
72
  readonly excluded: readonly PrismaEntityAbsence[];
62
73
  readonly exemptions: readonly PrismaReaderExemption[];
74
+ /**
75
+ * What the step made of the configuration's computed fields: read, or why
76
+ * not. Absent when it was given no configuration.
77
+ */
78
+ readonly computedFields?: ConfigComputedFieldsReading;
63
79
  };
64
80
  export declare function resolveInstalledPrismaCli(): PrismaCli;
65
81
  /**
@@ -1,19 +1,21 @@
1
1
  import { execFile } from "node:child_process";
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import ts from "typescript";
6
6
  import { computeModelHash } from "../discovery/artifact.loader.js";
7
+ import { DISCOVERY_ARTIFACT_FORMAT } from "../discovery/discovery-artifact.interface.js";
7
8
  import { readPrismaSchema } from "../discovery/schema.reader.js";
8
9
  import { readPrismaCapabilitySurface } from "../discovery/types.reader.js";
9
10
  import { emitDiscoveryArtifactModule } from "./artifact.emitter.js";
11
+ import { readConfigComputedFields, } from "./computed-fields.reader.js";
10
12
  import { readDeclaredSupport } from "./declared-support.reader.js";
11
13
  import { applyExistenceGate } from "./existence.gate.js";
12
14
  import { resolvePrismaCli } from "./prisma-cli.resolver.js";
13
15
  import { crossCheckReaders, describeReaderFindings, } from "./reader-crosscheck.js";
14
16
  export const PINNED_PRISMA_MAJOR = 7;
15
- export class PrismaGenerateStepError extends Error {
16
- name = "PrismaGenerateStepError";
17
+ export class AvPrismaGenerateStepError extends Error {
18
+ name = "AvPrismaGenerateStepError";
17
19
  }
18
20
  const run = promisify(execFile);
19
21
  export function resolveInstalledPrismaCli() {
@@ -22,7 +24,7 @@ export function resolveInstalledPrismaCli() {
22
24
  range: readDeclaredSupport().prisma,
23
25
  });
24
26
  if (resolution.kind === "refused") {
25
- throw new PrismaGenerateStepError(resolution.reason);
27
+ throw new AvPrismaGenerateStepError(resolution.reason);
26
28
  }
27
29
  return resolution.cli;
28
30
  }
@@ -35,7 +37,7 @@ function assertClassicCompilerApi() {
35
37
  typeof compiler.resolveModuleName === "function") {
36
38
  return;
37
39
  }
38
- throw new PrismaGenerateStepError(`the installed \`typescript\` ${compiler?.version ?? "(no version)"} has no classic compiler API (\`createProgram\`), which this step reads the generated client's types with; install \`typescript\` in this adapter's declared range ${readDeclaredSupport().typescript}.`);
40
+ throw new AvPrismaGenerateStepError(`the installed \`typescript\` ${compiler?.version ?? "(no version)"} has no classic compiler API (\`createProgram\`), which this step reads the generated client's types with; install \`typescript\` in this adapter's declared range ${readDeclaredSupport().typescript}.`);
39
41
  }
40
42
  export function clientRuntimeResolves(clientDirectory) {
41
43
  const containing = path.join(path.resolve(clientDirectory), "models", "_.ts");
@@ -85,6 +87,11 @@ async function writeArtifactAtomically(file, source) {
85
87
  throw error;
86
88
  }
87
89
  }
90
+ async function describesModel(file, modelHash) {
91
+ const current = await readFile(file, "utf8").catch(() => undefined);
92
+ return (current?.includes(`\tregenerate_with_aventara_prepare: ${DISCOVERY_ARTIFACT_FORMAT},\n`) === true &&
93
+ current.includes(`\tmodelHash: ${JSON.stringify(modelHash)},\n`));
94
+ }
88
95
  function majorOf(version) {
89
96
  const major = /^(\d+)\./.exec(version)?.[1];
90
97
  return major === undefined ? undefined : Number(major);
@@ -92,29 +99,45 @@ function majorOf(version) {
92
99
  function assertPinnedMajor(version) {
93
100
  const major = majorOf(version);
94
101
  if (major === undefined) {
95
- throw new PrismaGenerateStepError(`the installed \`prisma\` reports \`${version}\`, which is not a major.minor.patch version, so its major cannot be fenced against the pinned major ${PINNED_PRISMA_MAJOR}.`);
102
+ throw new AvPrismaGenerateStepError(`the installed \`prisma\` reports \`${version}\`, which is not a major.minor.patch version, so its major cannot be fenced against the pinned major ${PINNED_PRISMA_MAJOR}.`);
96
103
  }
97
104
  if (major !== PINNED_PRISMA_MAJOR) {
98
- throw new PrismaGenerateStepError(`the installed \`prisma\` is major ${major} and this adapter's readers are written against pinned major ${PINNED_PRISMA_MAJOR}. PSL's grammar and the generated client's shape are version-bound, so a new major stops the build here rather than producing an AdapterModel from a grammar nobody has read.`);
105
+ throw new AvPrismaGenerateStepError(`the installed \`prisma\` is major ${major} and this adapter's readers are written against pinned major ${PINNED_PRISMA_MAJOR}. PSL's grammar and the generated client's shape are version-bound, so a new major stops the build here rather than producing an AvAdapterModel from a grammar nobody has read.`);
99
106
  }
100
107
  }
101
108
  function assertClientRuntimeResolves(toolchain, clientDirectory) {
102
109
  if (toolchain.clientRuntimeResolves(clientDirectory)) {
103
110
  return;
104
111
  }
105
- throw new PrismaGenerateStepError(`\`@prisma/client/runtime/client\` does not resolve from ${clientDirectory}, so nothing read from the generated types can be trusted. This failure is SILENT by construction: every generated file opens \`// @ts-nocheck\`, so a program over the tree reports zero diagnostics while \`FieldRef\` degrades to its uninstantiated form and \`JsonValue\` stops being a union — flipping a types-derived nullability from \`true\` to \`false\` with no signal anywhere. Install \`@prisma/client\` where the generated output can resolve it, then regenerate.`);
112
+ throw new AvPrismaGenerateStepError(`\`@prisma/client/runtime/client\` does not resolve from ${clientDirectory}, so nothing read from the generated types can be trusted. This failure is SILENT by construction: every generated file opens \`// @ts-nocheck\`, so a program over the tree reports zero diagnostics while \`FieldRef\` degrades to its uninstantiated form and \`JsonValue\` stops being a union — flipping a types-derived nullability from \`true\` to \`false\` with no signal anywhere. Install \`@prisma/client\` where the generated output can resolve it, then regenerate.`);
113
+ }
114
+ async function assertArtifactPlacement(artifactFile, clientDirectory) {
115
+ const file = path.resolve(artifactFile);
116
+ const client = path.resolve(clientDirectory);
117
+ const relative = path.relative(client, file);
118
+ const outside = relative === ".." ||
119
+ relative.startsWith(`..${path.sep}`) ||
120
+ path.isAbsolute(relative);
121
+ if (!outside) {
122
+ throw new AvPrismaGenerateStepError(`the artifact file ${file} (--out) is inside the generated client's directory ${client} (--client), which the next \`prisma generate\` clears; write it outside that directory.`);
123
+ }
124
+ const existing = await stat(file).catch(() => undefined);
125
+ if (existing?.isDirectory() === true) {
126
+ throw new AvPrismaGenerateStepError(`the artifact file ${file} (--out) is a directory; name the .ts file to write, such as ${path.join(file, "discovery.artifact.ts")}.`);
127
+ }
106
128
  }
107
129
  function assertNothingUnhandled(facts) {
108
130
  if (facts.unhandled.length === 0) {
109
131
  return;
110
132
  }
111
- throw new PrismaGenerateStepError([
133
+ throw new AvPrismaGenerateStepError([
112
134
  "the schema reader located constructs it does not model, and a silently dropped construct is how a grammar change becomes wrong output instead of a build stop:",
113
135
  ...facts.unhandled.map((unknown) => ` - ${unknown.spelling} (${unknown.kind}) in \`${unknown.block ?? "<top level>"}\` at ${unknown.site.file}:${unknown.site.line}: ${unknown.text}`),
114
136
  ].join("\n"));
115
137
  }
116
138
  export async function runPrismaGenerateStep(request) {
117
139
  const toolchain = request.toolchain ?? createPrismaGenerateToolchain();
140
+ await assertArtifactPlacement(request.artifactFile, request.clientDirectory);
118
141
  const prismaVersion = await toolchain.installedPrismaVersion();
119
142
  assertPinnedMajor(prismaVersion);
120
143
  assertClientRuntimeResolves(toolchain, request.clientDirectory);
@@ -126,29 +149,42 @@ export async function runPrismaGenerateStep(request) {
126
149
  surface = toolchain.readSurface(request.clientDirectory);
127
150
  }
128
151
  catch (cause) {
129
- throw new PrismaGenerateStepError(`the capability surface at ${request.clientDirectory} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
152
+ throw new AvPrismaGenerateStepError(`the capability surface at ${request.clientDirectory} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
130
153
  }
131
154
  const { admitted, excluded } = applyExistenceGate(facts, surface);
132
155
  const { findings, exemptions } = crossCheckReaders(facts, surface);
133
156
  if (findings.length > 0) {
134
- throw new PrismaGenerateStepError(describeReaderFindings(findings));
157
+ throw new AvPrismaGenerateStepError(describeReaderFindings(findings));
135
158
  }
136
- const { model, translation, referentialActions, createRequirements } = request.composeModel({
159
+ const { model, translation, referentialActions } = request.composeModel({
137
160
  facts,
138
161
  surface,
139
162
  admitted,
140
163
  });
141
- const source = await emitDiscoveryArtifactModule({
164
+ const emission = {
142
165
  prismaVersion,
143
166
  provider: request.provider,
144
167
  model,
145
168
  translation,
146
169
  referentialActions,
147
170
  client: clientShapeOf(surface),
148
- createRequirements,
171
+ };
172
+ const modelHash = await computeModelHash(model);
173
+ let computedFields;
174
+ if (request.config !== undefined) {
175
+ if (!(await describesModel(request.artifactFile, modelHash))) {
176
+ await toolchain.writeArtifact(request.artifactFile, await emitDiscoveryArtifactModule({
177
+ ...emission,
178
+ computedFields: null,
179
+ }));
180
+ }
181
+ computedFields = (toolchain.readComputedFields ?? readConfigComputedFields)(request.config);
182
+ }
183
+ const source = await emitDiscoveryArtifactModule({
184
+ ...emission,
185
+ computedFields: computedFields?.kind === "read" ? computedFields.computedFields : null,
149
186
  });
150
187
  await toolchain.writeArtifact(request.artifactFile, source);
151
- const modelHash = await computeModelHash(model);
152
188
  return {
153
189
  artifactFile: request.artifactFile,
154
190
  source,
@@ -156,6 +192,7 @@ export async function runPrismaGenerateStep(request) {
156
192
  admitted,
157
193
  excluded,
158
194
  exemptions,
195
+ ...(computedFields === undefined ? {} : { computedFields }),
159
196
  };
160
197
  }
161
198
  function clientShapeOf(surface) {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export type { PrismaAdapterModel, PrismaDiscoveryArtifact, PrismaReferentialAction, PrismaReferentialActionTable, PrismaReferentialEdge, PrismaResourceReferentialActions, } from "./discovery/discovery-artifact.interface.js";
2
- export type { PrismaAdapterOptions } from "./prisma.adapter.js";
1
+ export type { AvPrismaAdapterModel, AvPrismaDiscoveryArtifact, AvPrismaReferentialAction, AvPrismaReferentialActionTable, AvPrismaReferentialEdge, AvPrismaResourceReferentialActions, } from "./discovery/discovery-artifact.interface.js";
2
+ export type { AvPrismaAdapterOptions } from "./prisma.adapter.js";
3
3
  export { createPrismaAdapter } from "./prisma.adapter.js";
4
- export type { PrismaDelegate, PrismaDelegateHost, PrismaDelegateIndex, PrismaTransactionOptions, } from "./prisma-client.interface.js";
5
- export type { PrismaDriver, PrismaIsolationLevel, PrismaProvider, PrismaProviderProfile, } from "./provider/provider-profile.js";
4
+ export type { AvPrismaDelegate, AvPrismaDelegateHost, AvPrismaDelegateIndex, AvPrismaTransactionOptions, } from "./prisma-client.interface.js";
5
+ export type { AvPrismaDriver, AvPrismaIsolationLevel, AvPrismaProvider, AvPrismaProviderProfile, } from "./provider/provider-profile.js";
@@ -1,23 +1,37 @@
1
- import type { PrismaIsolationLevel } from "./provider/provider-profile.js";
1
+ import type { AvPrismaIsolationLevel } from "./provider/provider-profile.js";
2
2
  /** Prisma interactive-transaction options. */
3
- export type PrismaTransactionOptions = {
3
+ export type AvPrismaTransactionOptions = {
4
4
  readonly maxWait?: number;
5
5
  readonly timeout?: number;
6
- readonly isolationLevel?: PrismaIsolationLevel;
6
+ readonly isolationLevel?: AvPrismaIsolationLevel;
7
7
  };
8
8
  /** One Prisma model delegate, such as `prisma.user`. */
9
- export type PrismaDelegate = Readonly<Record<string, unknown>>;
9
+ export type AvPrismaDelegate = Readonly<Record<string, unknown>>;
10
10
  /** The Prisma client shape the adapter accepts. */
11
- export interface PrismaDelegateHost {
11
+ export interface AvPrismaDelegateHost {
12
12
  /** Prisma's interactive `$transaction`. */
13
- $transaction<T>(work: (transactional: PrismaDelegateHost) => Promise<T>, options?: PrismaTransactionOptions): Promise<T>;
13
+ $transaction<T>(work: (transactional: AvPrismaDelegateHost) => Promise<T>, options?: AvPrismaTransactionOptions): Promise<T>;
14
14
  }
15
15
  /** A Prisma client's model delegates, by name. */
16
- export type PrismaDelegateIndex = Readonly<Record<string, PrismaDelegate | undefined>>;
16
+ export type AvPrismaDelegateIndex = Readonly<Record<string, AvPrismaDelegate | undefined>>;
17
17
  /**
18
18
  * The single place the structural gap between a generated client (a class,
19
19
  * with no index signature) and a delegate index is crossed. Every delegate
20
20
  * lookup in the adapter goes through here, so there is exactly one assertion
21
21
  * to audit rather than one per call site.
22
22
  */
23
- export declare function prismaDelegates(client: PrismaDelegateHost): PrismaDelegateIndex;
23
+ export declare function prismaDelegates(client: AvPrismaDelegateHost): AvPrismaDelegateIndex;
24
+ /**
25
+ * A tagged template's strings as `$queryRaw` reads them: the static text pieces,
26
+ * with their `raw` twin.
27
+ */
28
+ export type PrismaSqlTemplate = readonly string[] & {
29
+ readonly raw: readonly string[];
30
+ };
31
+ /** `tx.$queryRaw`, called in its tagged-template form: every value bound. */
32
+ export type PrismaRawQuery = (template: PrismaSqlTemplate, ...values: readonly unknown[]) => PromiseLike<unknown>;
33
+ /**
34
+ * A client's `$queryRaw` (the base client or a transaction client), bound to it: the single place the gap
35
+ * between the structural host and a client's raw query is crossed.
36
+ */
37
+ export declare function prismaRawQuery(client: AvPrismaDelegateHost): PrismaRawQuery | undefined;
@@ -1,3 +1,10 @@
1
1
  export function prismaDelegates(client) {
2
2
  return client;
3
3
  }
4
+ export function prismaRawQuery(client) {
5
+ const query = client
6
+ .$queryRaw;
7
+ return typeof query === "function"
8
+ ? query.bind(client)
9
+ : undefined;
10
+ }
@@ -1,29 +1,29 @@
1
- import type { Adapter } from "@aventara/core";
2
- import type { PrismaAdapterModel, PrismaDiscoveryArtifact } from "./discovery/discovery-artifact.interface.js";
3
- import type { PrismaDelegateHost, PrismaTransactionOptions } from "./prisma-client.interface.js";
4
- import { type PrismaDriver, type PrismaProvider } from "./provider/provider-profile.js";
1
+ import type { AvAdapter } from "@aventara/core";
2
+ import type { AvPrismaAdapterModel, AvPrismaDiscoveryArtifact } from "./discovery/discovery-artifact.interface.js";
3
+ import type { AvPrismaDelegateHost, AvPrismaTransactionOptions } from "./prisma-client.interface.js";
4
+ import { type AvPrismaDriver, type AvPrismaProvider } from "./provider/provider-profile.js";
5
5
  /** Options for {@link createPrismaAdapter}. */
6
- export type PrismaAdapterOptions<TClient extends PrismaDelegateHost, M extends PrismaAdapterModel = PrismaAdapterModel> = {
6
+ export type AvPrismaAdapterOptions<TClient extends AvPrismaDelegateHost, M extends AvPrismaAdapterModel = AvPrismaAdapterModel> = {
7
7
  /** Your constructed Prisma client. */
8
8
  readonly client: TClient;
9
9
  /** The `discovery` export of the generated discovery artifact. */
10
- readonly discovery: PrismaDiscoveryArtifact<M>;
10
+ readonly discovery: AvPrismaDiscoveryArtifact<M>;
11
11
  /** The database provider the client was generated for. */
12
- readonly provider: PrismaProvider;
12
+ readonly provider: AvPrismaProvider;
13
13
  /** The Prisma driver adapter the client is constructed with. */
14
- readonly driver: PrismaDriver;
14
+ readonly driver: AvPrismaDriver;
15
15
  /** Options passed to every Prisma interactive transaction. */
16
- readonly transactionOptions?: PrismaTransactionOptions;
16
+ readonly transactionOptions?: AvPrismaTransactionOptions;
17
17
  };
18
18
  /**
19
- * The installed client's version, resolved by the caller.
19
+ * The adapter's options, plus the installed client's version as an override.
20
20
  *
21
21
  * `@prisma/client` is a *peer* dependency, so the version that matters is the
22
- * one installed beside the application, not beside this package. The caller
23
- * supplies it; `createPrismaAdapter` does not go looking, which is also what
24
- * keeps the construction path free of Prisma tooling.
22
+ * one installed beside the application. `createPrismaAdapter` reads it from
23
+ * `@prisma/client/package.json` itself (`discovery/installed-client.locator.ts`);
24
+ * `installedPrismaVersion`, when given, is used instead (tests).
25
25
  */
26
- export type PrismaAdapterConstruction<TClient extends PrismaDelegateHost, M extends PrismaAdapterModel = PrismaAdapterModel> = PrismaAdapterOptions<TClient, M> & {
26
+ export type PrismaAdapterConstruction<TClient extends AvPrismaDelegateHost, M extends AvPrismaAdapterModel = AvPrismaAdapterModel> = AvPrismaAdapterOptions<TClient, M> & {
27
27
  readonly installedPrismaVersion?: string;
28
28
  };
29
29
  /**
@@ -40,7 +40,7 @@ export type PrismaAdapterConstruction<TClient extends PrismaDelegateHost, M exte
40
40
  * });
41
41
  * ```
42
42
  *
43
- * @throws `PrismaDiscoveryArtifactError` when the artifact is stale, corrupt or
43
+ * @throws `AvPrismaDiscoveryArtifactError` when the artifact is stale, corrupt or
44
44
  * was generated for another Prisma major; its message says how to regenerate it.
45
45
  */
46
- export declare function createPrismaAdapter<TClient extends PrismaDelegateHost, M extends PrismaAdapterModel = PrismaAdapterModel>(options: PrismaAdapterConstruction<TClient, M>): Promise<Adapter<M>>;
46
+ export declare function createPrismaAdapter<TClient extends AvPrismaDelegateHost, M extends AvPrismaAdapterModel = AvPrismaAdapterModel>(options: PrismaAdapterConstruction<TClient, M>): Promise<AvAdapter<M>>;