@prisma-next/cli 0.5.0-dev.9 → 0.6.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +61 -26
  2. package/dist/cli-errors-B9OBbled.d.mts +3 -0
  3. package/dist/cli-errors-D3_sMh2K.mjs +33 -0
  4. package/dist/cli-errors-D3_sMh2K.mjs.map +1 -0
  5. package/dist/cli.mjs +16 -78
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/client-qVH-rEgd.mjs +1595 -0
  8. package/dist/client-qVH-rEgd.mjs.map +1 -0
  9. package/dist/{result-handler-Ba3zWQsI.mjs → command-helpers-BeZHkxV8.mjs} +70 -47
  10. package/dist/command-helpers-BeZHkxV8.mjs.map +1 -0
  11. package/dist/commands/contract-emit.d.mts.map +1 -1
  12. package/dist/commands/contract-emit.mjs +2 -4
  13. package/dist/commands/contract-infer.d.mts.map +1 -1
  14. package/dist/commands/contract-infer.mjs +2 -4
  15. package/dist/commands/db-init.d.mts.map +1 -1
  16. package/dist/commands/db-init.mjs +16 -13
  17. package/dist/commands/db-init.mjs.map +1 -1
  18. package/dist/commands/db-schema.d.mts.map +1 -1
  19. package/dist/commands/db-schema.mjs +6 -7
  20. package/dist/commands/db-schema.mjs.map +1 -1
  21. package/dist/commands/db-sign.d.mts.map +1 -1
  22. package/dist/commands/db-sign.mjs +9 -9
  23. package/dist/commands/db-sign.mjs.map +1 -1
  24. package/dist/commands/db-update.d.mts.map +1 -1
  25. package/dist/commands/db-update.mjs +15 -13
  26. package/dist/commands/db-update.mjs.map +1 -1
  27. package/dist/commands/db-verify.d.mts.map +1 -1
  28. package/dist/commands/db-verify.mjs +1 -321
  29. package/dist/commands/migration-apply.d.mts +28 -13
  30. package/dist/commands/migration-apply.d.mts.map +1 -1
  31. package/dist/commands/migration-apply.mjs +55 -151
  32. package/dist/commands/migration-apply.mjs.map +1 -1
  33. package/dist/commands/migration-new.d.mts +0 -1
  34. package/dist/commands/migration-new.d.mts.map +1 -1
  35. package/dist/commands/migration-new.mjs +34 -40
  36. package/dist/commands/migration-new.mjs.map +1 -1
  37. package/dist/commands/migration-plan.d.mts +33 -6
  38. package/dist/commands/migration-plan.d.mts.map +1 -1
  39. package/dist/commands/migration-plan.mjs +2 -348
  40. package/dist/commands/migration-ref.d.mts +1 -1
  41. package/dist/commands/migration-ref.d.mts.map +1 -1
  42. package/dist/commands/migration-ref.mjs +8 -12
  43. package/dist/commands/migration-ref.mjs.map +1 -1
  44. package/dist/commands/migration-show.d.mts +13 -7
  45. package/dist/commands/migration-show.d.mts.map +1 -1
  46. package/dist/commands/migration-show.mjs +35 -36
  47. package/dist/commands/migration-show.mjs.map +1 -1
  48. package/dist/commands/migration-status.d.mts +126 -5
  49. package/dist/commands/migration-status.d.mts.map +1 -1
  50. package/dist/commands/migration-status.mjs +2 -4
  51. package/dist/{config-loader-C25b63rJ.mjs → config-loader-B6sJjXTv.mjs} +3 -5
  52. package/dist/config-loader-B6sJjXTv.mjs.map +1 -0
  53. package/dist/config-loader.d.mts +0 -1
  54. package/dist/config-loader.d.mts.map +1 -1
  55. package/dist/config-loader.mjs +2 -3
  56. package/dist/contract-emit-9DBda5Ou.mjs +150 -0
  57. package/dist/contract-emit-9DBda5Ou.mjs.map +1 -0
  58. package/dist/contract-emit-B77TsJqf.mjs +327 -0
  59. package/dist/contract-emit-B77TsJqf.mjs.map +1 -0
  60. package/dist/{contract-enrichment-CAOELa-H.mjs → contract-enrichment-Dani0mMW.mjs} +4 -6
  61. package/dist/contract-enrichment-Dani0mMW.mjs.map +1 -0
  62. package/dist/{contract-infer-D9cC3rJm.mjs → contract-infer-BK9YFGEG.mjs} +13 -22
  63. package/dist/contract-infer-BK9YFGEG.mjs.map +1 -0
  64. package/dist/db-verify-C0y1PCO2.mjs +404 -0
  65. package/dist/db-verify-C0y1PCO2.mjs.map +1 -0
  66. package/dist/exports/config-types.mjs +1 -2
  67. package/dist/exports/control-api.d.mts +101 -586
  68. package/dist/exports/control-api.d.mts.map +1 -1
  69. package/dist/exports/control-api.mjs +4 -6
  70. package/dist/exports/index.d.mts.map +1 -1
  71. package/dist/exports/index.mjs +28 -30
  72. package/dist/exports/index.mjs.map +1 -1
  73. package/dist/exports/init-output.d.mts +2 -4
  74. package/dist/exports/init-output.d.mts.map +1 -1
  75. package/dist/exports/init-output.mjs +2 -3
  76. package/dist/extension-pack-inputs-C7xgE-vv.mjs +74 -0
  77. package/dist/extension-pack-inputs-C7xgE-vv.mjs.map +1 -0
  78. package/dist/{framework-components-Cr--XBKy.mjs → framework-components-ChqVUxR-.mjs} +3 -4
  79. package/dist/{framework-components-Cr--XBKy.mjs.map → framework-components-ChqVUxR-.mjs.map} +1 -1
  80. package/dist/global-flags-Icqpxk23.d.mts +12 -0
  81. package/dist/global-flags-Icqpxk23.d.mts.map +1 -0
  82. package/dist/helpers-eqdN8tH6.mjs +25 -0
  83. package/dist/helpers-eqdN8tH6.mjs.map +1 -0
  84. package/dist/{init-C5220SY9.mjs → init-DETSgw3h.mjs} +40 -49
  85. package/dist/init-DETSgw3h.mjs.map +1 -0
  86. package/dist/{inspect-live-schema-yrHAvG71.mjs → inspect-live-schema-CWYxGKlb.mjs} +10 -11
  87. package/dist/inspect-live-schema-CWYxGKlb.mjs.map +1 -0
  88. package/dist/migration-cli.d.mts +41 -12
  89. package/dist/migration-cli.d.mts.map +1 -1
  90. package/dist/migration-cli.mjs +309 -86
  91. package/dist/migration-cli.mjs.map +1 -1
  92. package/dist/{migration-command-scaffold-B3B09et6.mjs → migration-command-scaffold-B5dORFEv.mjs} +8 -9
  93. package/dist/migration-command-scaffold-B5dORFEv.mjs.map +1 -0
  94. package/dist/migration-plan-C6lVaHsO.mjs +554 -0
  95. package/dist/migration-plan-C6lVaHsO.mjs.map +1 -0
  96. package/dist/{migration-status-DUMiH8_G.mjs → migration-status-CZ-D5k7k.mjs} +272 -65
  97. package/dist/migration-status-CZ-D5k7k.mjs.map +1 -0
  98. package/dist/migrations-D_UJnpuW.mjs +216 -0
  99. package/dist/migrations-D_UJnpuW.mjs.map +1 -0
  100. package/dist/{output-BpcQrnnq.mjs → output-B16Kefzx.mjs} +9 -3
  101. package/dist/output-B16Kefzx.mjs.map +1 -0
  102. package/dist/{progress-adapter-DvQWB1nK.mjs → progress-adapter-DFfvZcYL.mjs} +2 -2
  103. package/dist/{progress-adapter-DvQWB1nK.mjs.map → progress-adapter-DFfvZcYL.mjs.map} +1 -1
  104. package/dist/result-handler-rmPVKIP2.mjs +25 -0
  105. package/dist/result-handler-rmPVKIP2.mjs.map +1 -0
  106. package/dist/rolldown-runtime-twds-ZHy.mjs +14 -0
  107. package/dist/{terminal-ui-C3ZLwQxK.mjs → terminal-ui-C_hFNbAn.mjs} +4 -28
  108. package/dist/terminal-ui-C_hFNbAn.mjs.map +1 -0
  109. package/dist/types-D7x-IFLO.d.mts +858 -0
  110. package/dist/types-D7x-IFLO.d.mts.map +1 -0
  111. package/dist/{verify-Bkycc-Tf.mjs → verify-CiwNWM9N.mjs} +3 -4
  112. package/dist/verify-CiwNWM9N.mjs.map +1 -0
  113. package/package.json +28 -26
  114. package/src/cli.ts +32 -6
  115. package/src/commands/contract-emit.ts +67 -163
  116. package/src/commands/contract-infer.ts +7 -20
  117. package/src/commands/db-init.ts +15 -3
  118. package/src/commands/db-update.ts +9 -4
  119. package/src/commands/db-verify.ts +47 -15
  120. package/src/commands/init/index.ts +1 -1
  121. package/src/commands/init/init.ts +2 -2
  122. package/src/commands/init/templates/code-templates.ts +26 -18
  123. package/src/commands/inspect-live-schema.ts +10 -5
  124. package/src/commands/migration-apply.ts +114 -212
  125. package/src/commands/migration-new.ts +42 -45
  126. package/src/commands/migration-plan.ts +212 -72
  127. package/src/commands/migration-ref.ts +8 -7
  128. package/src/commands/migration-show.ts +60 -41
  129. package/src/commands/migration-status.ts +483 -64
  130. package/src/config-path-validation.ts +0 -1
  131. package/src/control-api/client.ts +85 -5
  132. package/src/control-api/contract-enrichment.ts +6 -4
  133. package/src/control-api/operations/apply-aggregate.ts +290 -0
  134. package/src/control-api/operations/contract-emit.ts +198 -115
  135. package/src/control-api/operations/db-apply-aggregate.ts +397 -0
  136. package/src/control-api/operations/db-init.ts +51 -253
  137. package/src/control-api/operations/db-update.ts +66 -183
  138. package/src/control-api/operations/db-verify.ts +342 -0
  139. package/src/control-api/operations/migration-apply.ts +424 -131
  140. package/src/control-api/types.ts +280 -29
  141. package/src/exports/control-api.ts +15 -3
  142. package/src/load-ts-contract.ts +28 -26
  143. package/src/migration-cli.ts +445 -122
  144. package/src/utils/cli-errors.ts +49 -2
  145. package/src/utils/combine-schema-results.ts +84 -0
  146. package/src/utils/command-helpers.ts +69 -25
  147. package/src/utils/contract-space-aggregate-loader.ts +204 -0
  148. package/src/utils/contract-space-extension-migrations-pass.ts +120 -0
  149. package/src/utils/contract-space-migrate-pass.ts +156 -0
  150. package/src/utils/emit-queue.ts +26 -0
  151. package/src/utils/extension-pack-inputs.ts +170 -0
  152. package/src/utils/formatters/graph-migration-mapper.ts +7 -3
  153. package/src/utils/formatters/migrations.ts +197 -61
  154. package/src/utils/publish-contract-artifact-pair.ts +134 -0
  155. package/dist/cli-errors-BFYgBH3L.d.mts +0 -4
  156. package/dist/cli-errors-Cd79vmTH.mjs +0 -5
  157. package/dist/client-CrsnY58k.mjs +0 -997
  158. package/dist/client-CrsnY58k.mjs.map +0 -1
  159. package/dist/commands/db-verify.mjs.map +0 -1
  160. package/dist/commands/migration-plan.mjs.map +0 -1
  161. package/dist/config-loader-C25b63rJ.mjs.map +0 -1
  162. package/dist/contract-emit--feXyNd7.mjs +0 -4
  163. package/dist/contract-emit-NJ01hiiv.mjs +0 -195
  164. package/dist/contract-emit-NJ01hiiv.mjs.map +0 -1
  165. package/dist/contract-emit-V5SSitUT.mjs +0 -122
  166. package/dist/contract-emit-V5SSitUT.mjs.map +0 -1
  167. package/dist/contract-enrichment-CAOELa-H.mjs.map +0 -1
  168. package/dist/contract-infer-D9cC3rJm.mjs.map +0 -1
  169. package/dist/extract-operation-statements-DsFfxXVZ.mjs +0 -13
  170. package/dist/extract-operation-statements-DsFfxXVZ.mjs.map +0 -1
  171. package/dist/extract-sql-ddl-D9UbZDyz.mjs +0 -26
  172. package/dist/extract-sql-ddl-D9UbZDyz.mjs.map +0 -1
  173. package/dist/init-C5220SY9.mjs.map +0 -1
  174. package/dist/inspect-live-schema-yrHAvG71.mjs.map +0 -1
  175. package/dist/migration-command-scaffold-B3B09et6.mjs.map +0 -1
  176. package/dist/migration-status-DUMiH8_G.mjs.map +0 -1
  177. package/dist/migrations-Bo5WtTla.mjs +0 -153
  178. package/dist/migrations-Bo5WtTla.mjs.map +0 -1
  179. package/dist/output-BpcQrnnq.mjs.map +0 -1
  180. package/dist/result-handler-Ba3zWQsI.mjs.map +0 -1
  181. package/dist/terminal-ui-C3ZLwQxK.mjs.map +0 -1
  182. package/dist/validate-contract-deps-B_Cs29TL.mjs +0 -37
  183. package/dist/validate-contract-deps-B_Cs29TL.mjs.map +0 -1
  184. package/dist/verify-Bkycc-Tf.mjs.map +0 -1
  185. package/src/control-api/operations/extract-operation-statements.ts +0 -14
  186. package/src/control-api/operations/extract-sql-ddl.ts +0 -47
@@ -1,4 +1,4 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
1
+ import { mkdir } from 'node:fs/promises';
2
2
  import type { Contract } from '@prisma-next/contract/types';
3
3
  import { emit, getEmittedArtifactPaths } from '@prisma-next/emitter';
4
4
  import { createControlStack } from '@prisma-next/framework-components/control';
@@ -7,57 +7,156 @@ import { ifDefined } from '@prisma-next/utils/defined';
7
7
  import { dirname } from 'pathe';
8
8
  import { loadConfig } from '../../config-loader';
9
9
  import { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';
10
+ import { queueEmitByOutput } from '../../utils/emit-queue';
10
11
  import { assertFrameworkComponentsCompatible } from '../../utils/framework-components';
12
+ import { publishContractArtifactPair } from '../../utils/publish-contract-artifact-pair';
13
+ import { validateContractDeps } from '../../utils/validate-contract-deps';
11
14
  import { enrichContract } from '../contract-enrichment';
12
- import type { ContractEmitOptions, ContractEmitResult } from '../types';
15
+ import type {
16
+ ContractEmitOptions,
17
+ ContractEmitResult,
18
+ ControlActionName,
19
+ OnControlProgress,
20
+ } from '../types';
13
21
 
14
- interface ProviderFailureLike {
15
- readonly summary: string;
16
- readonly diagnostics: readonly unknown[];
17
- readonly meta?: unknown;
18
- }
22
+ const EMIT_ACTION: ControlActionName = 'emit';
19
23
 
20
24
  function isRecord(value: unknown): value is Record<string, unknown> {
21
25
  return typeof value === 'object' && value !== null;
22
26
  }
23
27
 
24
- function isAbortError(error: unknown): boolean {
25
- return isRecord(error) && typeof error['name'] === 'string' && error['name'] === 'AbortError';
28
+ function startSpan(onProgress: OnControlProgress | undefined, spanId: string, label: string): void {
29
+ onProgress?.({ action: EMIT_ACTION, kind: 'spanStart', spanId, label });
30
+ }
31
+
32
+ function endSpan(
33
+ onProgress: OnControlProgress | undefined,
34
+ spanId: string,
35
+ outcome: 'ok' | 'error',
36
+ ): void {
37
+ onProgress?.({ action: EMIT_ACTION, kind: 'spanEnd', spanId, outcome });
38
+ }
39
+
40
+ function failedToResolveContractSource(why: string, fix: string, meta?: Record<string, unknown>) {
41
+ return errorRuntime('Failed to resolve contract source', {
42
+ why,
43
+ fix,
44
+ ...ifDefined('meta', meta),
45
+ });
46
+ }
47
+
48
+ type ValidatedProviderResult =
49
+ | { readonly ok: true; readonly value: unknown }
50
+ | { readonly ok: false; readonly error: ReturnType<typeof errorRuntime> };
51
+
52
+ function diagnosticLocationSuffix(diagnostic: Record<string, unknown>): string {
53
+ const sourceId = typeof diagnostic['sourceId'] === 'string' ? diagnostic['sourceId'] : undefined;
54
+ const span = isRecord(diagnostic['span']) ? diagnostic['span'] : undefined;
55
+ const start = span && isRecord(span['start']) ? span['start'] : undefined;
56
+ const line = start && typeof start['line'] === 'number' ? start['line'] : undefined;
57
+ const column = start && typeof start['column'] === 'number' ? start['column'] : undefined;
58
+ if (sourceId && line !== undefined && column !== undefined) {
59
+ return ` (${sourceId}:${line}:${column})`;
60
+ }
61
+ if (sourceId) {
62
+ return ` (${sourceId})`;
63
+ }
64
+ return '';
26
65
  }
27
66
 
28
- function isProviderFailureLike(value: unknown): value is ProviderFailureLike {
29
- return (
30
- isRecord(value) && typeof value['summary'] === 'string' && Array.isArray(value['diagnostics'])
31
- );
67
+ function mapDiagnosticsToIssues(
68
+ diagnostics: readonly unknown[],
69
+ ): ReadonlyArray<{ readonly kind: string; readonly message: string }> {
70
+ const issues: { readonly kind: string; readonly message: string }[] = [];
71
+ for (const raw of diagnostics) {
72
+ if (!isRecord(raw)) continue;
73
+ const code = typeof raw['code'] === 'string' ? raw['code'] : 'diagnostic';
74
+ const message = typeof raw['message'] === 'string' ? raw['message'] : '';
75
+ issues.push({ kind: code, message: `${message}${diagnosticLocationSuffix(raw)}` });
76
+ }
77
+ return issues;
78
+ }
79
+
80
+ function validateProviderResult(providerResult: unknown): ValidatedProviderResult {
81
+ if (!isRecord(providerResult) || typeof providerResult['ok'] !== 'boolean') {
82
+ return {
83
+ ok: false,
84
+ error: failedToResolveContractSource(
85
+ 'Contract source provider returned malformed result shape.',
86
+ 'Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).',
87
+ ),
88
+ };
89
+ }
90
+
91
+ if (providerResult['ok']) {
92
+ if (!('value' in providerResult)) {
93
+ return {
94
+ ok: false,
95
+ error: failedToResolveContractSource(
96
+ 'Contract source provider returned malformed success result: missing value.',
97
+ 'Ensure contract.source.load success payload is ok(Contract).',
98
+ ),
99
+ };
100
+ }
101
+ return { ok: true, value: providerResult['value'] };
102
+ }
103
+
104
+ const failure = providerResult['failure'];
105
+ if (
106
+ !isRecord(failure) ||
107
+ typeof failure['summary'] !== 'string' ||
108
+ !Array.isArray(failure['diagnostics'])
109
+ ) {
110
+ return {
111
+ ok: false,
112
+ error: failedToResolveContractSource(
113
+ 'Contract source provider returned malformed failure result: expected summary and diagnostics.',
114
+ 'Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).',
115
+ ),
116
+ };
117
+ }
118
+ return {
119
+ ok: false,
120
+ error: failedToResolveContractSource(
121
+ String(failure['summary']),
122
+ 'Fix contract source diagnostics and return ok(Contract).',
123
+ {
124
+ diagnostics: failure['diagnostics'],
125
+ issues: mapDiagnosticsToIssues(failure['diagnostics']),
126
+ ...ifDefined('providerMeta', failure['meta']),
127
+ },
128
+ ),
129
+ };
32
130
  }
33
131
 
34
132
  /**
35
- * Executes the contract emit operation.
133
+ * Canonical contract emit operation.
36
134
  *
37
- * This is an offline operation that:
38
- * 1. Loads the Prisma Next config from the specified path
39
- * 2. Resolves the contract source from config
40
- * 3. Creates a control plane stack and family instance
41
- * 4. Emits contract artifacts (JSON and DTS)
42
- * 5. Writes files to the paths specified in config
135
+ * This is the SINGLE publication path used by both the CLI command
136
+ * (`prisma-next contract emit`) and the Vite plugin
137
+ * (`@prisma-next/vite-plugin-contract-emit`). New callers must go through this
138
+ * function rather than re-implementing load emit publish.
43
139
  *
44
- * Supports AbortSignal for cancellation, enabling "last change wins" behavior.
140
+ * The whole flow (load config resolve source → emit bytes → atomic publish)
141
+ * is serialized per output JSON path via `queueEmitByOutput`. Concurrent calls
142
+ * for the same output line up FIFO; the user-visible outcome is "last
143
+ * submission wins on disk" without any supersession bookkeeping. Within a
144
+ * single emit, `publishContractArtifactPair` stages temp files, renames
145
+ * `contract.d.ts` before `contract.json`, and attempts to restore the previous
146
+ * pair if either rename fails — so type-only consumers never observe a
147
+ * mismatched pair.
45
148
  *
46
- * @param options - Options including configPath and optional signal
47
- * @returns File paths and hashes of emitted artifacts
48
- * @throws If config loading fails, contract is invalid, or file I/O fails
49
- * @throws signal.reason if cancelled via AbortSignal (typically DOMException with name 'AbortError')
149
+ * @throws {CliStructuredError} on config/source/validation problems
150
+ * @throws {DOMException} `AbortError` if cancelled via `signal`
50
151
  */
51
152
  export async function executeContractEmit(
52
153
  options: ContractEmitOptions,
53
154
  ): Promise<ContractEmitResult> {
54
- const { configPath, signal = new AbortController().signal } = options;
155
+ const { configPath, signal = new AbortController().signal, onProgress } = options;
55
156
  const unlessAborted = abortable(signal);
56
157
 
57
- // Load config using the existing config loader
58
158
  const config = await unlessAborted(loadConfig(configPath));
59
159
 
60
- // Validate contract config is present
61
160
  if (!config.contract) {
62
161
  throw errorContractConfigMissing({
63
162
  why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }',
@@ -66,14 +165,12 @@ export async function executeContractEmit(
66
165
 
67
166
  const contractConfig = config.contract;
68
167
 
69
- // Validate output path is present and ends with .json
70
168
  if (!contractConfig.output) {
71
169
  throw errorContractConfigMissing({
72
170
  why: 'Contract config must have output path. This should not happen if defineConfig() was used.',
73
171
  });
74
172
  }
75
173
 
76
- // Validate source exists and is callable
77
174
  if (typeof contractConfig.source?.load !== 'function') {
78
175
  throw errorContractConfigMissing({
79
176
  why: 'Contract config must include a valid source provider object',
@@ -90,98 +187,84 @@ export async function executeContractEmit(
90
187
  }
91
188
  const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;
92
189
 
93
- const stack = createControlStack(config);
190
+ return queueEmitByOutput(outputJsonPath, async () => {
191
+ const stack = createControlStack(config);
94
192
 
95
- const sourceContext = {
96
- composedExtensionPacks: stack.extensionPacks.map((p) => p.id),
97
- scalarTypeDescriptors: stack.scalarTypeDescriptors,
98
- authoringContributions: stack.authoringContributions,
99
- codecLookup: stack.codecLookup,
100
- controlMutationDefaults: stack.controlMutationDefaults,
101
- resolvedInputs: contractConfig.source.inputs ?? [],
102
- };
193
+ const sourceContext = {
194
+ composedExtensionPacks: stack.extensionPacks.map((p) => p.id),
195
+ scalarTypeDescriptors: stack.scalarTypeDescriptors,
196
+ authoringContributions: stack.authoringContributions,
197
+ codecLookup: stack.codecLookup,
198
+ controlMutationDefaults: stack.controlMutationDefaults,
199
+ resolvedInputs: contractConfig.source.inputs ?? [],
200
+ };
103
201
 
104
- let providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>;
105
- try {
106
- providerResult = await unlessAborted(contractConfig.source.load(sourceContext));
107
- } catch (error) {
108
- if (signal.aborted || isAbortError(error)) {
109
- throw error;
202
+ startSpan(onProgress, 'resolveSource', 'Resolving contract source...');
203
+ let providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>;
204
+ try {
205
+ providerResult = await unlessAborted(contractConfig.source.load(sourceContext));
206
+ } catch (error) {
207
+ endSpan(onProgress, 'resolveSource', 'error');
208
+ if (signal.aborted || (isRecord(error) && error['name'] === 'AbortError')) {
209
+ throw error;
210
+ }
211
+ throw failedToResolveContractSource(
212
+ error instanceof Error ? error.message : String(error),
213
+ 'Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.',
214
+ );
110
215
  }
111
- throw errorRuntime('Failed to resolve contract source', {
112
- why: error instanceof Error ? error.message : String(error),
113
- fix: 'Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.',
114
- });
115
- }
116
216
 
117
- if (!isRecord(providerResult) || typeof providerResult.ok !== 'boolean') {
118
- throw errorRuntime('Failed to resolve contract source', {
119
- why: 'Contract source provider returned malformed result shape.',
120
- fix: 'Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).',
121
- });
122
- }
123
-
124
- if (providerResult.ok && !('value' in providerResult)) {
125
- throw errorRuntime('Failed to resolve contract source', {
126
- why: 'Contract source provider returned malformed success result: missing value.',
127
- fix: 'Ensure contract.source.load success payload is ok(Contract).',
128
- });
129
- }
217
+ const validatedContract = validateProviderResult(providerResult);
218
+ if (!validatedContract.ok) {
219
+ endSpan(onProgress, 'resolveSource', 'error');
220
+ throw validatedContract.error;
221
+ }
222
+ endSpan(onProgress, 'resolveSource', 'ok');
130
223
 
131
- if (!providerResult.ok && !isProviderFailureLike(providerResult.failure)) {
132
- throw errorRuntime('Failed to resolve contract source', {
133
- why: 'Contract source provider returned malformed failure result: expected summary and diagnostics.',
134
- fix: 'Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).',
135
- });
136
- }
224
+ startSpan(onProgress, 'emit', 'Emitting contract...');
225
+ let emitResult: Awaited<ReturnType<typeof emit>>;
226
+ try {
227
+ const familyInstance = config.family.create(stack);
228
+ const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
229
+ const frameworkComponents = assertFrameworkComponentsCompatible(
230
+ config.family.familyId,
231
+ config.target.targetId,
232
+ rawComponents,
233
+ );
234
+ const enrichedIR = enrichContract(validatedContract.value as Contract, frameworkComponents);
235
+ familyInstance.validateContract(enrichedIR);
236
+ emitResult = await unlessAborted(
237
+ emit(enrichedIR, stack, config.family.emission, { outputJsonPath }),
238
+ );
239
+ } catch (error) {
240
+ endSpan(onProgress, 'emit', 'error');
241
+ throw error;
242
+ }
243
+ endSpan(onProgress, 'emit', 'ok');
137
244
 
138
- if (!providerResult.ok) {
139
- throw errorRuntime('Failed to resolve contract source', {
140
- why: providerResult.failure.summary,
141
- fix: 'Fix contract source diagnostics and return ok(Contract).',
142
- meta: {
143
- diagnostics: providerResult.failure.diagnostics,
144
- ...ifDefined('providerMeta', providerResult.failure.meta),
145
- },
245
+ await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));
246
+ await publishContractArtifactPair({
247
+ outputJsonPath,
248
+ outputDtsPath,
249
+ contractJson: emitResult.contractJson,
250
+ contractDts: emitResult.contractDts,
251
+ publicationToken: String(process.hrtime.bigint()),
146
252
  });
147
- }
148
253
 
149
- const familyInstance = config.family.create(stack);
150
-
151
- const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
152
- const frameworkComponents = assertFrameworkComponentsCompatible(
153
- config.family.familyId,
154
- config.target.targetId,
155
- rawComponents,
156
- );
157
- const enrichedIR = enrichContract(providerResult.value as Contract, frameworkComponents);
158
-
159
- familyInstance.validateContract(enrichedIR);
160
- const emitResult = await unlessAborted(
161
- emit(enrichedIR, stack, config.family.emission, {
162
- outputJsonPath: outputJsonPath,
163
- }),
164
- );
165
-
166
- // Create directory if needed and write files (both colocated)
167
- await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));
168
- await unlessAborted(writeFile(outputJsonPath, emitResult.contractJson, 'utf-8'));
169
- await unlessAborted(writeFile(outputDtsPath, emitResult.contractDts, 'utf-8'));
170
-
171
- // Validate that contract.d.ts type imports are resolvable
172
- const { validateContractDeps } = await import('../../utils/validate-contract-deps');
173
- const depsValidation = validateContractDeps(emitResult.contractDts, dirname(outputDtsPath));
174
- if (depsValidation.warning) {
175
- process.stderr.write(`\n⚠ ${depsValidation.warning}\n`);
176
- }
254
+ const validationWarning = validateContractDeps(
255
+ emitResult.contractDts,
256
+ dirname(outputDtsPath),
257
+ ).warning;
177
258
 
178
- return {
179
- storageHash: emitResult.storageHash,
180
- ...ifDefined('executionHash', emitResult.executionHash),
181
- profileHash: emitResult.profileHash,
182
- files: {
183
- json: outputJsonPath,
184
- dts: outputDtsPath,
185
- },
186
- };
259
+ return {
260
+ storageHash: emitResult.storageHash,
261
+ ...ifDefined('executionHash', emitResult.executionHash),
262
+ profileHash: emitResult.profileHash,
263
+ files: {
264
+ json: outputJsonPath,
265
+ dts: outputDtsPath,
266
+ },
267
+ ...ifDefined('validationWarning', validationWarning),
268
+ };
269
+ });
187
270
  }