|
2 | 2 |
|
3 | 3 | import path from 'path'; |
4 | 4 | import fs from 'fs'; |
| 5 | +import { createRequire } from 'node:module'; |
| 6 | +import { pathToFileURL } from 'node:url'; |
5 | 7 | import chalk from 'chalk'; |
6 | 8 | import { bundleRequire } from 'bundle-require'; |
| 9 | +import type { Plugin } from 'esbuild'; |
7 | 10 | import { printError } from './format.js'; |
8 | 11 |
|
9 | 12 | export interface LoadedConfig { |
@@ -72,17 +75,173 @@ export function resolveConfigPath(source?: string): string { |
72 | 75 | process.exit(1); |
73 | 76 | } |
74 | 77 |
|
| 78 | +/** |
| 79 | + * Every `@objectstack/spec` entrypoint an authored config can reach the |
| 80 | + * `define*` helpers through — the root and every subpath export. Real projects |
| 81 | + * use both: the example apps import `defineView`/`defineApp` from |
| 82 | + * `@objectstack/spec/ui` and `defineHook`/`defineDatasource` from |
| 83 | + * `@objectstack/spec/data`, so a shim that knew only the root package would |
| 84 | + * cover the smaller half of the authored surface. |
| 85 | + */ |
| 86 | +const SPEC_MODULE_RE = /^@objectstack\/spec(?:\/[\w./-]+)?$/; |
| 87 | + |
| 88 | +/** esbuild namespace the authored-source shim modules live in. */ |
| 89 | +const AUTHORED_SOURCE_NAMESPACE = 'objectstack-authored-source'; |
| 90 | + |
| 91 | +/** `defineStack`, `defineView`, … — the authoring helpers, by naming convention. */ |
| 92 | +const DEFINE_HELPER_RE = /^define[A-Z]/; |
| 93 | + |
| 94 | +/** |
| 95 | + * The `define*` helpers a given `@objectstack/spec` entrypoint exports, read |
| 96 | + * from the copy **the config itself would import** (resolved from the config's |
| 97 | + * own directory, not the CLI's). |
| 98 | + * |
| 99 | + * Returns `[]` — i.e. "shim nothing" — when the entrypoint cannot be resolved |
| 100 | + * or imported. That is the safe direction: an unshimmed load is exactly |
| 101 | + * today's behaviour, so a project the enumeration cannot read is no worse off |
| 102 | + * than before. |
| 103 | + */ |
| 104 | +async function defineHelpersOf(specifier: string, requireFromConfig: NodeRequire): Promise<string[]> { |
| 105 | + try { |
| 106 | + const resolved = requireFromConfig.resolve(specifier); |
| 107 | + const ns = (await import(pathToFileURL(resolved).href)) as Record<string, unknown>; |
| 108 | + return Object.keys(ns).filter((k) => DEFINE_HELPER_RE.test(k) && typeof ns[k] === 'function'); |
| 109 | + } catch { |
| 110 | + return []; |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Load an authored config **as authored**, for the one consumer whose input is |
| 116 | + * a source the CURRENT schema is expected to refuse: the `os migrate meta` |
| 117 | + * codemod (#9418). |
| 118 | + * |
| 119 | + * ## The defect this exists to close |
| 120 | + * |
| 121 | + * A retired authorable key is a `retiredKey()` tombstone — `z.never()` carrying |
| 122 | + * the upgrade prescription — so the current schema does not strip it, it |
| 123 | + * REJECTS it. Every `define*` helper in `@objectstack/spec` is a |
| 124 | + * `Schema.parse(config)`, and a real `objectstack.config.ts` calls them: `os |
| 125 | + * init` scaffolds `export default defineStack({ … })`, and larger projects |
| 126 | + * spread `defineView` / `defineAgent` / `defineFlow` across per-artifact |
| 127 | + * modules. So the rejection happens while the config MODULE is being evaluated, |
| 128 | + * inside `bundleRequire` — before `os migrate meta` has run a line of its own. |
| 129 | + * |
| 130 | + * The CLI never had a validation step to reorder: the gate lives in the loaded |
| 131 | + * module. That made the codemod refuse the only input class it exists for, and |
| 132 | + * the refusal it printed was the prescription telling the author to run it — |
| 133 | + * `Run \`os migrate meta --from <N>\`…` ships 144 times across 39 files under |
| 134 | + * `packages/spec/src`, so the upgrade path closed a loop on itself. |
| 135 | + * |
| 136 | + * ## What the shim does |
| 137 | + * |
| 138 | + * Each `@objectstack/spec` entrypoint the config imports is replaced by a |
| 139 | + * generated module that re-exports the real one and wraps its `define*` |
| 140 | + * helpers as **try-real-then-authored**: |
| 141 | + * |
| 142 | + * ```js |
| 143 | + * export const defineView = (...authored) => { |
| 144 | + * try { return realDefineView(...authored); } catch { return authored[0]; } |
| 145 | + * }; |
| 146 | + * ``` |
| 147 | + * |
| 148 | + * The narrowness is the point, and it is what keeps this a restoration rather |
| 149 | + * than a widening of what the command accepts: |
| 150 | + * |
| 151 | + * - **A source that loads today loads identically.** The real helper runs, so |
| 152 | + * its defaults and transforms still apply (`defineForm` moves `schemaId` |
| 153 | + * into `data`, `defineStack` merges actions into objects, …). Nothing about |
| 154 | + * the existing happy path is re-decided. |
| 155 | + * - **A source the current schema refuses reaches the chain as authored** — |
| 156 | + * which is precisely the codemod's input. `defineX(config: z.input<typeof |
| 157 | + * XSchema>)` means the authored argument is by construction a shape |
| 158 | + * `XSchema` accepts, so handing it on unparsed yields a well-formed |
| 159 | + * authoring tree rather than an ad-hoc one. |
| 160 | + * - **Validation is not skipped, it is moved after the conversion.** The |
| 161 | + * command still parses the MIGRATED stack through |
| 162 | + * `ObjectStackDefinitionSchema` and reports `schemaValid`, so a source that |
| 163 | + * is broken for reasons the chain cannot fix is still reported as broken — |
| 164 | + * just after the codemod has done the part it can. |
| 165 | + * |
| 166 | + * A swallowed verdict is announced on **stderr** rather than dropped: the |
| 167 | + * author deserves to know an artifact bypassed the parse, and stderr keeps a |
| 168 | + * `--json` run's stdout a single parseable document. |
| 169 | + * |
| 170 | + * ⚠️ Deliberately NOT the default for `loadConfig()`. Every other command — |
| 171 | + * `os build`, `os validate`, `os serve` — must keep hearing the rejection: the |
| 172 | + * tombstone IS their upgrade channel. Only the codemod is entitled to read |
| 173 | + * past it. |
| 174 | + */ |
| 175 | +function authoredSourcePlugin(configPath: string): Plugin { |
| 176 | + const requireFromConfig = createRequire(configPath); |
| 177 | + return { |
| 178 | + name: 'objectstack:authored-source', |
| 179 | + setup(build) { |
| 180 | + build.onResolve({ filter: SPEC_MODULE_RE }, (args) => { |
| 181 | + // The shim re-exports the SAME specifier it stands in for. Left to |
| 182 | + // resolve normally that import would land back here and shim itself |
| 183 | + // forever, so inside the namespace the specifier is handed straight to |
| 184 | + // the runtime — which is also what keeps `__real` the project's own |
| 185 | + // copy of spec rather than the CLI's. |
| 186 | + if (args.namespace === AUTHORED_SOURCE_NAMESPACE) { |
| 187 | + return { path: args.path, external: true }; |
| 188 | + } |
| 189 | + return { path: args.path, namespace: AUTHORED_SOURCE_NAMESPACE }; |
| 190 | + }); |
| 191 | + |
| 192 | + build.onLoad({ filter: /.*/, namespace: AUTHORED_SOURCE_NAMESPACE }, async (args) => { |
| 193 | + const helpers = await defineHelpersOf(args.path, requireFromConfig); |
| 194 | + const spec = JSON.stringify(args.path); |
| 195 | + const lines = [ |
| 196 | + `import * as __real from ${spec};`, |
| 197 | + `export * from ${spec};`, |
| 198 | + ]; |
| 199 | + for (const name of helpers) { |
| 200 | + lines.push( |
| 201 | + `export const ${name} = (...authored) => {`, |
| 202 | + ` try {`, |
| 203 | + ` return __real.${name}(...authored);`, |
| 204 | + ` } catch (error) {`, |
| 205 | + ` console.warn(`, |
| 206 | + ` '[authored-source] ' + ${JSON.stringify(name)} + '(): the current schema refuses this '`, |
| 207 | + ` + 'artifact, so it is handed to the migration chain exactly as authored. '`, |
| 208 | + ` + ((error && error.message) || String(error)),`, |
| 209 | + ` );`, |
| 210 | + ` return authored[0];`, |
| 211 | + ` }`, |
| 212 | + `};`, |
| 213 | + ); |
| 214 | + } |
| 215 | + return { contents: lines.join('\n'), loader: 'js' }; |
| 216 | + }); |
| 217 | + }, |
| 218 | + }; |
| 219 | +} |
| 220 | + |
| 221 | +export interface LoadConfigOptions { |
| 222 | + /** |
| 223 | + * Read the config as AUTHORED rather than as the current schema would have |
| 224 | + * it — see {@link authoredSourcePlugin}. Set by `os migrate meta` only. |
| 225 | + * |
| 226 | + * @default false |
| 227 | + */ |
| 228 | + authoredSource?: boolean; |
| 229 | +} |
| 230 | + |
75 | 231 | /** |
76 | 232 | * Load and bundle a config file using bundle-require. |
77 | 233 | * Returns the resolved config object and load time. |
78 | 234 | */ |
79 | | -export async function loadConfig(source?: string): Promise<LoadedConfig> { |
| 235 | +export async function loadConfig(source?: string, options?: LoadConfigOptions): Promise<LoadedConfig> { |
80 | 236 | const absolutePath = resolveConfigPath(source); |
81 | 237 | const start = Date.now(); |
82 | 238 |
|
83 | 239 | const { mod } = await bundleRequire({ |
84 | 240 | filepath: absolutePath, |
85 | 241 | external: BUNDLE_REQUIRE_EXTERNALS, |
| 242 | + ...(options?.authoredSource |
| 243 | + ? { esbuildOptions: { plugins: [authoredSourcePlugin(absolutePath)] } } |
| 244 | + : {}), |
86 | 245 | }); |
87 | 246 |
|
88 | 247 | const baseConfig = mod.default || mod; |
|
0 commit comments