Skip to content

Commit 7254769

Browse files
committed
chore(cli): simplify round 12 — workspace from the directory at the request layer, stored-edges under the printed typing
- resolveProfile is back to flag, env and config. The terminal reads the workspace the working directory names once before each action (enclosingWorkspace, the same rule recordedWorkspace uses: base, workspace folder, starter), and actingProfileFrom/clientFrom apply it below --workspace and SIM_WORKSPACE. 'directory' leaves SettingSource; whoami and the 404 wording read workspaceDirectory. sim login needs no opt-out. A starter directory now chooses the workspace for every command, as it does for source create. - explicitWorkspaceSetting lives in config and is the one "flag then env" check. - .sim/stored-edges.json digests blocks under the child results the get printed with: a workspace get/apply types each folder by the folders it answered with, a workflow get, create or apply into a workspace folder by that workspace directory's folders. The check compares its typed compile directly, so the untyped recompile is gone. - A workspace check compiles each workflow once, with its env names, and reuses that compile for a workflow whose calls no child result types.
1 parent c5b93c7 commit 7254769

22 files changed

Lines changed: 431 additions & 262 deletions

‎packages/sim-cli/src/commands/auth.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ function presentAuthentication(source: SettingSource): {
106106
return { configured: true, source: 'credentials' }
107107
case 'unset':
108108
return { configured: false, source: 'unset' }
109-
case 'directory':
110109
case 'config':
111110
case 'default':
112111
throw new SimApiError(`Unexpected credential source "${source}".`, 0)
@@ -572,11 +571,8 @@ export function loginCommand(): Command {
572571
.option('--callback-port <port>', 'Pin the local port the browser returns to')
573572
.option('-y, --yes', 'Overwrite an existing API-key profile without prompting')
574573
.action(async (options: LoginOptions, command: Command) => {
575-
/**
576-
* Login may name the profile it is about to create. It stores the workspace the key defaults
577-
* to as the profile's, so a source directory it runs in must not choose that workspace.
578-
*/
579-
const profile = profileFrom(command, { allowUnknownProfile: true, cwd: undefined })
574+
/** Login may name the profile it is about to create. */
575+
const profile = profileFrom(command, { allowUnknownProfile: true })
580576
const authProfile = resolveAuthenticationProfileName(profile.name)
581577

582578
if (authProfile !== profile.name) {
@@ -1144,7 +1140,7 @@ export function whoamiCommand(): Command {
11441140
sources: {
11451141
endpoint: sources.endpoint,
11461142
authentication: authentication.source,
1147-
workspaceId: sources.workspaceId,
1143+
workspaceId: profile.workspaceDirectory ? 'directory' : sources.workspaceId,
11481144
output: sources.output,
11491145
},
11501146
verification: {

‎packages/sim-cli/src/commands/protocol/source-check.ts‎

Lines changed: 58 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import {
1212
type CanonicalWorkflow,
1313
type ChildResultFields,
1414
calledWorkflowKey,
15-
calledWorkflowKeys,
1615
catalogBlock,
1716
childResultFields,
1817
codeFrame,
@@ -50,9 +49,11 @@ import {
5049
readSourceText,
5150
unchangedTexts,
5251
type Written,
52+
workspaceFolderOf,
5353
} from './source-dir'
5454
import { STRICT_FINDINGS } from './source-strict'
5555
import {
56+
cachedCatalog,
5657
cachedSourceCatalog,
5758
type LocalDeclarations,
5859
refreshTsconfigs,
@@ -61,7 +62,13 @@ import {
6162
} from './source-tree'
6263
import { type TypeCheck, typeCheck } from './source-types'
6364
import { type Diagnostic, findingsOutput } from './source-ui'
64-
import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges'
65+
import {
66+
blockDigest,
67+
type ChildResults,
68+
compiledWithChildResults,
69+
readStoredBlockDigests,
70+
readStoredEdges,
71+
} from './stored-edges'
6572
import { lockRecoveryHint, readSourceFiles } from './workflow-dir'
6673
import {
6774
type DeclaredColumn,
@@ -459,13 +466,13 @@ function declarationFindings(
459466
/**
460467
* Compiles the workflow source directory `dir` against the catalog its base names when that one is
461468
* cached (a workflow holding a type the workspace catalog lacks was printed with its own), else
462-
* `catalog`, checking env names against the names `secrets.ts` declares when `declarations` hold
463-
* them.
469+
* `catalog`, checking env names against `envNames` (what `secrets.ts` declares) when given. Its
470+
* calls are untyped: {@link compiledWithChildResults} types them.
464471
*/
465472
async function compileWorkflowDir(
466473
dir: string,
467474
workspaceCatalog: BlockCatalog,
468-
declarations?: WorkspaceDeclarations
475+
envNames?: ReadonlySet<string>
469476
) {
470477
const lockText = await readSourceText(dir, SOURCE_LOCK_FILE)
471478
const parsedLock = lockText === null ? null : parseWorkflowLock(lockText)
@@ -477,8 +484,6 @@ async function compileWorkflowDir(
477484
cachedSourceCatalog(dir),
478485
])
479486
const catalog = printedWith ?? workspaceCatalog
480-
const envNames = declarations?.envNames
481-
const childResults = declarations?.childResults
482487
const input: Parameters<typeof compileWorkflow>[0] = {
483488
entry: { path: SOURCE_ENTRY_FILE, text: files[SOURCE_ENTRY_FILE] },
484489
files: new Map(Object.entries(files).filter(([path]) => path !== SOURCE_ENTRY_FILE)),
@@ -489,25 +494,20 @@ async function compileWorkflowDir(
489494
...(storedEdges ? { storedUnreadEdges: storedEdges } : {}),
490495
...(envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}),
491496
}
492-
const compiled = compileWorkflow({ ...input, ...(childResults ? { childResults } : {}) })
493-
// `.sim/stored-edges.json` digests each block as the printed source compiles with no child
494-
// results, so a block typed by one counts as changed only when its source did.
495-
const typesCall =
496-
compiled.workflow !== null &&
497-
calledWorkflowKeys(compiled.workflow).some((key) => childResults?.has(key))
498-
const digested = typesCall ? compileWorkflow(input).workflow : compiled.workflow
499497
return {
500498
lock,
501499
lockProblems: parsedLock?.diagnostics ?? [],
502500
files,
503-
compiled,
504-
digested,
501+
input,
502+
compiled: compileWorkflow(input),
505503
storedBlocks,
506504
printedWith,
507505
catalog,
508506
}
509507
}
510508

509+
type CompiledWorkflowDir = Awaited<ReturnType<typeof compileWorkflowDir>>
510+
511511
/** What {@link readCheckDeclarations} reads: the declarations and the compiled workflows' facts. */
512512
type CheckDeclarations = WorkspaceDeclarations &
513513
Awaited<ReturnType<typeof compileWorkspaceWorkflows>>
@@ -518,33 +518,49 @@ type CheckDeclarations = WorkspaceDeclarations &
518518
* (`startInputs`, `null` without a Start trigger), which `workspace.d.ts` also types
519519
* `inputMapping` with, the keys of those that end at a Response block on every run, whose
520520
* `result` is that block's output, and the typed fields of the data each of those responds with,
521-
* which type a call's `<call.result.data.<field>>`.
521+
* which type a call's `<call.result.data.<field>>`. Each compile is kept (`compiledWorkflows`, by
522+
* key) for {@link checkWorkflowDir}: env names change only its findings, never its blocks.
522523
*/
523524
export async function readCheckDeclarations(
524525
root: string,
525526
catalog: BlockCatalog
526527
): Promise<CheckDeclarations> {
527-
const [declared, workflows] = await Promise.all([
528-
readWorkspaceDeclarations(root),
529-
compileWorkspaceWorkflows(root, catalog),
530-
])
531-
return { ...declared, ...workflows }
528+
const declared = await readWorkspaceDeclarations(root)
529+
return { ...declared, ...(await compileWorkspaceWorkflows(root, catalog, declared.envNames)) }
532530
}
533531

534-
async function compileWorkspaceWorkflows(root: string, catalog: BlockCatalog) {
532+
async function compileWorkspaceWorkflows(
533+
root: string,
534+
catalog: BlockCatalog,
535+
envNames?: ReadonlySet<string>
536+
) {
535537
const workflowInputs = new Map<string, WorkflowInput[] | null>()
536538
const respondingWorkflows = new Set<string>()
537539
const childResults = new Map<string, ChildResultFields>()
540+
const compiledWorkflows = new Map<string, CompiledWorkflowDir>()
538541
for (const key of await workspaceWorkflowKeys(root)) {
539-
const dir = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog)
542+
const dir = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog, envNames)
543+
compiledWorkflows.set(key, dir)
540544
const { workflow } = dir.compiled
541545
if (!workflow) continue
542546
workflowInputs.set(key, startInputs(workflow))
543547
if (respondsOnEveryRun(workflow)) respondingWorkflows.add(key)
544548
const fields = childResultFields(workflow, dir.catalog)
545549
if (fields) childResults.set(key, fields)
546550
}
547-
return { workflowInputs, respondingWorkflows, childResults }
551+
return { workflowInputs, respondingWorkflows, childResults, compiledWorkflows }
552+
}
553+
554+
/**
555+
* The child results that type the calls of a workflow written into `dir`, as a check of it types
556+
* them: those of the workspace directory it is a workflow folder of, compiled from disk against
557+
* the workspace's cached catalog; `undefined` for a workflow directory of its own, which has none.
558+
*/
559+
export async function folderChildResults(dir: string): Promise<ChildResults | undefined> {
560+
const folder = await workspaceFolderOf(dir)
561+
const catalog = folder && cachedCatalog(folder.workspaceId)
562+
if (!folder || !catalog) return undefined
563+
return (await compileWorkspaceWorkflows(folder.root, catalog)).childResults
548564
}
549565

550566
/**
@@ -618,10 +634,23 @@ async function writtenWorkspaceTypes(
618634
export async function checkWorkflowDir(
619635
dir: string,
620636
catalog: BlockCatalog,
621-
options: { declarations?: WorkspaceDeclarations; strict: StrictMode; prefix?: string }
637+
options: {
638+
declarations?: CheckDeclarations
639+
strict: StrictMode
640+
/** The key of the workflow folder `dir` is, whose compile `declarations` hold. */
641+
key?: string
642+
prefix?: string
643+
}
622644
): Promise<{ findings: CheckFinding[]; entry: string; unlisted: UnlistedCounts }> {
623-
const compiledDir = await compileWorkflowDir(dir, catalog, options.declarations)
624-
const { lock, lockProblems, files, compiled, digested, storedBlocks, printedWith } = compiledDir
645+
const { declarations } = options
646+
const untyped =
647+
(options.key === undefined ? undefined : declarations?.compiledWorkflows.get(options.key)) ??
648+
(await compileWorkflowDir(dir, catalog, declarations?.envNames))
649+
const compiledDir = {
650+
...untyped,
651+
compiled: compiledWithChildResults(untyped.input, untyped.compiled, declarations?.childResults),
652+
}
653+
const { lock, lockProblems, files, compiled, storedBlocks, printedWith } = compiledDir
625654
const entryText = files[SOURCE_ENTRY_FILE]
626655
const locate = (block: string, param: string, names: string | undefined) => {
627656
const prefix = encodeAnchor({ kind: 'param', block, param: '' })
@@ -685,7 +714,7 @@ export async function checkWorkflowDir(
685714
*/
686715
const changed = (blockKey: string) => {
687716
if (!bound(blockKey) || moved(blockKey)) return true
688-
const block = digested?.blocks[blockKey]
717+
const block = compiled.workflow?.blocks[blockKey]
689718
const printed = printedWith ? storedBlocks?.get(blockKey) : undefined
690719
return block !== undefined && printed !== undefined && blockDigest(block) !== printed
691720
}

‎packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts‎

Lines changed: 48 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { toRecord } from '@sim/utils/object'
88
import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
99
import { KIND_DIRS } from '@sim/workspace-code'
1010
import type { Command } from 'commander'
11-
import type { ResolvedProfile } from '../../../config/index'
11+
import { explicitWorkspaceSetting, type ResolvedProfile } from '../../../config/index'
1212
import { embedStore } from '../../../embed-context'
1313
import { SourceDirError } from '../local-errors'
1414
import { readSourceJson, readSourceText } from './files'
@@ -28,15 +28,6 @@ export function absoluteDirOption(command: Command): Command {
2828
})
2929
}
3030

31-
/**
32-
* The setting that named the resolved workspace explicitly, `--workspace` or `SIM_WORKSPACE`, or
33-
* `null` when the workspace came from a source directory, the profile, or nowhere.
34-
*/
35-
function explicitWorkspaceSetting(profile: Pick<ResolvedProfile, 'sources'>): string | null {
36-
const source = profile.sources.workspaceId
37-
return source === 'flag' ? '--workspace' : source === 'env' ? 'SIM_WORKSPACE' : null
38-
}
39-
4031
/**
4132
* The workspace a source command acts on for a directory read from `readFrom`: that workspace,
4233
* whatever the profile's default, so a directory stays bound to where it came from. A
@@ -107,21 +98,60 @@ export async function readStarterWorkspace(dir: string): Promise<string | null>
10798
return typeof workspaceId === 'string' ? workspaceId : null
10899
}
109100

101+
/** The workspace a source directory names, and the directory whose record names it. */
102+
export interface NamedWorkspace {
103+
workspaceId: string
104+
/** `dir` itself, or the workspace directory it is a workflow folder of. */
105+
dir: string
106+
/** Whether a starter's record names it, which an explicit workspace overrides. */
107+
starter: boolean
108+
}
109+
110110
/**
111-
* The workspace `dir` records it belongs to: the one its `.sim/base.json` was read from, else the
111+
* The workspace `dir` names: the one its `.sim/base.json` was read from, else that of the
112112
* workspace directory it is a workflow folder of, else the one its starter's types were written
113-
* for (`null` when none). A starter yields to a `--workspace` or `SIM_WORKSPACE`, which chooses
114-
* another; a base or workspace folder does not ({@link directoryWorkspace} refuses either).
113+
* for (`null` when none). The one definition of the workspace a directory names, for a source
114+
* command's `--dir` ({@link recordedWorkspace}) and the directory any command runs in
115+
* ({@link enclosingWorkspace}).
116+
*/
117+
async function namedWorkspace(dir: string): Promise<NamedWorkspace | null> {
118+
const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE))
119+
if (typeof base.workspaceId === 'string') {
120+
return { workspaceId: base.workspaceId, dir, starter: false }
121+
}
122+
const folder = await workspaceFolderOf(dir)
123+
if (folder) return { workspaceId: folder.workspaceId, dir: folder.root, starter: false }
124+
const starter = await readStarterWorkspace(dir)
125+
return starter === null ? null : { workspaceId: starter, dir, starter: true }
126+
}
127+
128+
/**
129+
* The workspace `dir` records it belongs to ({@link namedWorkspace}). A starter yields to a
130+
* `--workspace` or `SIM_WORKSPACE`, which chooses another; a base or workspace folder does not
131+
* ({@link directoryWorkspace} refuses either).
115132
*/
116133
export async function recordedWorkspace(
117134
dir: string,
118135
profile: Pick<ResolvedProfile, 'sources'>
119136
): Promise<string | null> {
120-
const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE))
121-
if (typeof base.workspaceId === 'string') return base.workspaceId
122-
const folder = await workspaceFolderOf(dir)
123-
if (folder) return folder.workspaceId
124-
return explicitWorkspaceSetting(profile) === null ? readStarterWorkspace(dir) : null
137+
const named = await namedWorkspace(dir)
138+
if (!named || (named.starter && explicitWorkspaceSetting(profile) !== null)) return null
139+
return named.workspaceId
140+
}
141+
142+
/**
143+
* The workspace the nearest directory at or above `cwd` names ({@link namedWorkspace}), which a
144+
* command run in `cwd` acts on unless `--workspace` or `SIM_WORKSPACE` names one; `null` when none
145+
* up to the root names one.
146+
*/
147+
export async function enclosingWorkspace(cwd: string): Promise<NamedWorkspace | null> {
148+
for (let dir = resolve(cwd); ; dir = dirname(dir)) {
149+
// One whose records cannot be read (a symbolic link, no permission) names none: a directory
150+
// above the one a command runs in, such as a linked `~/.sim`, must not stop the command.
151+
const named = await namedWorkspace(dir).catch(() => null)
152+
if (named) return named
153+
if (dirname(dir) === dir) return null
154+
}
125155
}
126156

127157
/**

‎packages/sim-cli/src/commands/protocol/source-dir/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ export {
1616
absoluteDirOption,
1717
assertSourceDirKind,
1818
directoryWorkspace,
19+
enclosingWorkspace,
20+
type NamedWorkspace,
1921
readStarterWorkspace,
2022
recordedWorkspace,
2123
workspaceFolderOf,

0 commit comments

Comments
 (0)