farseer-cli 1.16.0 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +329 -1
- package/dist/commands/code.js +104 -0
- package/dist/commands/code.js.map +7 -0
- package/dist/commands/formula.js +16 -7
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/tool.js +120 -0
- package/dist/commands/tool.js.map +7 -0
- package/dist/index.js +21 -2
- package/dist/index.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +65 -23
- package/dist/mcp/tools/modelTools.js.map +3 -3
- package/dist/mcp/tools/runTools.js +6 -2
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/utils/launchPin.js +1 -1
- package/dist/mcp/utils/launchPin.js.map +2 -2
- package/dist/pipeline/service.js +1 -1
- package/dist/pipeline/service.js.map +2 -2
- package/dist/services/codefirst/api.js +269 -0
- package/dist/services/codefirst/api.js.map +7 -0
- package/dist/services/codefirst/binaryDisk.js +67 -0
- package/dist/services/codefirst/binaryDisk.js.map +7 -0
- package/dist/services/codefirst/byteHashes.js +129 -0
- package/dist/services/codefirst/byteHashes.js.map +7 -0
- package/dist/services/codefirst/documents.js +563 -0
- package/dist/services/codefirst/documents.js.map +7 -0
- package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
- package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
- package/dist/services/codefirst/layoutCompose.js +593 -0
- package/dist/services/codefirst/layoutCompose.js.map +7 -0
- package/dist/services/codefirst/layoutCore.js +260 -0
- package/dist/services/codefirst/layoutCore.js.map +7 -0
- package/dist/services/codefirst/layoutPaths.js +492 -0
- package/dist/services/codefirst/layoutPaths.js.map +7 -0
- package/dist/services/codefirst/layoutProjection.js +995 -0
- package/dist/services/codefirst/layoutProjection.js.map +7 -0
- package/dist/services/codefirst/layoutReadback.js +2552 -0
- package/dist/services/codefirst/layoutReadback.js.map +7 -0
- package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
- package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
- package/dist/services/codefirst/layoutReceipt.js +1592 -0
- package/dist/services/codefirst/layoutReceipt.js.map +7 -0
- package/dist/services/codefirst/layoutScan.js +882 -0
- package/dist/services/codefirst/layoutScan.js.map +7 -0
- package/dist/services/codefirst/output.js +179 -0
- package/dist/services/codefirst/output.js.map +7 -0
- package/dist/services/codefirst/types.js +17 -0
- package/dist/services/codefirst/types.js.map +7 -0
- package/dist/services/codefirst/workflow.js +581 -0
- package/dist/services/codefirst/workflow.js.map +7 -0
- package/dist/services/codefirst/workspace.js +310 -0
- package/dist/services/codefirst/workspace.js.map +7 -0
- package/dist/services/codefirst/workspaceLock.js +148 -0
- package/dist/services/codefirst/workspaceLock.js.map +7 -0
- package/dist/services/codefirst/workspaceRoot.js +147 -0
- package/dist/services/codefirst/workspaceRoot.js.map +7 -0
- package/dist/utils/formulaFilters.js +48 -0
- package/dist/utils/formulaFilters.js.map +7 -0
- package/dist/utils/logger.js +9 -3
- package/dist/utils/logger.js.map +2 -2
- package/docs/cli-guide.md +13 -0
- package/package.json +3 -2
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/services/codefirst/workflow.ts"],
|
|
4
|
+
"sourcesContent": ["import * as fs from 'fs';\nimport type { ErrorResponse } from 'farseer-client';\nimport * as path from 'path';\nimport { CodeFirstApi, requestSettled } from './api';\nimport { BLOB_UPLOAD_LIMIT, hashFile, sameBytes, type BlobApi } from './binaryDisk';\nimport { canonicalText, parseState, validateDocumentKeys } from './documents';\nimport { composeLayoutSubmission, submittedDocumentFiles, type ComposeLayoutSubmissionResult } from './layoutCompose';\nimport { canonicalFragmentHash } from './layoutCore';\nimport { rawBytesPath } from './layoutPaths';\nimport {\n bindLayoutReceiptSubmission,\n captureLayoutSubmissionComposition,\n type LayoutReceiptSubmission,\n type PhysicalMaterialization,\n type PreserveReason,\n} from './layoutReadback';\nimport {\n layoutReceiptDrafts,\n materializeLayoutPlan,\n quarantinedApplyAdvice,\n refuseUnwrittenReceipts,\n type LayoutPlanOutcome,\n} from './layoutReceipt';\nimport { loadLayoutByteEvidence, resolveLayoutPath, scanLayout, stateText } from './layoutScan';\nimport { layoutExitCode, renderNotices, renderPlan, renderReceipt } from './output';\nimport {\n ApplyingHead,\n Head,\n Json,\n LayoutReceiptDraft,\n Notice,\n Pending,\n Plan,\n PlanOperation,\n Receipt,\n State,\n} from './types';\nimport { saveLearnedByteHashes, saveState, STATE_FILE, workspacePath } from './workspace';\nimport { withWorkspaceLock } from './workspaceLock';\nimport { createCodeWorkspace, type CodeWorkspace } from './workspaceRoot';\nimport { TenantSession } from '../preflight';\n\n/** One resolved code workspace and the authenticated target its state names. */\nexport interface WorkspaceCommand extends CodeWorkspace {\n target: TenantSession;\n}\n\ntype CompleteComposition = Extract<ComposeLayoutSubmissionResult, { status: 'complete' }>;\n\nconst pause = () => new Promise<void>((resolve) => setTimeout(resolve, 2000));\nexport function waitSeconds(value: string): number {\n const seconds = Number(value);\n if (!Number.isFinite(seconds) || seconds < 0 || seconds > 3600)\n throw new Error('--wait-seconds must be between 0 and 3600');\n return seconds;\n}\nfunction loadState(root: string): State {\n if (!fs.existsSync(workspacePath(root, STATE_FILE)))\n throw new Error('No model workspace; run farseer code checkout <tenant> first');\n return parseState(stateText(root));\n}\n\n/**\n * Change one draft on the state as it is on disk now, never on a copy read earlier: another\n * command may have saved in between (a plan or a pull in another shell), and saving an older copy\n * would undo that save. Returns false when the draft is gone, so there is nothing to change.\n */\nfunction updateDraft(root: string, planId: string, change: (draft: LayoutReceiptDraft) => void): boolean {\n const current = loadState(root);\n const draft = current.layout.receipts[planId];\n if (!draft) return false;\n change(draft);\n saveState(root, current);\n return true;\n}\n\n/** What the author does when an apply request of `planId` may still be running on the server. */\nfunction unansweredApply(planId: string): string {\n return (\n `the apply request for plan p${planId} got no answer from the server, so it may still be running ` +\n `there; run farseer code apply p${planId} again, which resumes that apply and writes its receipt`\n );\n}\n\n/**\n * The API of one workspace command, refused when it would reach another server than the one the\n * workspace was checked out from. Plan ids are per-server sequences and a baseline names versions\n * only its own server stores, so `code apply 5` against another server would apply that server's\n * plan 5. `FARSEER_API_URL` or another stored credential is the usual way to get there.\n */\nfunction workspaceApi(workspace: WorkspaceCommand): CodeFirstApi {\n const api = new CodeFirstApi(workspace.target);\n const resolved = api.baseUrl();\n if (resolved !== workspace.state.baseUrl)\n throw new Error(\n `This workspace was checked out from ${workspace.state.baseUrl}, but this command would use ` +\n `${resolved}; run it with the credential and FARSEER_API_URL the workspace was checked out with`,\n );\n return api;\n}\n\n/**\n * Whether the server's stored plan is the one this workspace's draft recorded when it was created:\n * the same document keys, the same handles (the receipt writes assigned ids into files through\n * them), and per operation the same action, kind, key, handle, name and changed paths. The rendered\n * values are left out, because a stored plan's read masks job secrets for display.\n */\nfunction sameStoredPlan(stored: Plan, draft: LayoutReceiptSubmission): boolean {\n const operations = (items: readonly PlanOperation[]) =>\n items\n .map((op) =>\n canonicalText({\n action: op.action,\n kind: op.kind,\n key: op.key ?? null,\n handle: op.handle ?? null,\n name: op.name,\n paths: op.fieldDiff.map((diff) => diff.path),\n }),\n )\n .sort();\n return (\n canonicalText(stored.documentKeys ?? []) === canonicalText([...draft.documentKeys]) &&\n canonicalText((stored.handles ?? {}) as unknown as Json) === canonicalText(draft.handles as unknown as Json) &&\n canonicalText(operations(stored.operations ?? [])) === canonicalText(operations(draft.operations))\n );\n}\nfunction composeWorkspace(root: string, state: State): CompleteComposition {\n const evidence = {\n ...state.layout.evidence,\n groupedSubmissionProofs: [],\n binarySubmissionProofs: [],\n canonicalBaseline: state.baseline,\n };\n const scan = scanLayout({ root, tracked: state.layout.tracked });\n const composed = composeLayoutSubmission({\n scan,\n byteEvidence: loadLayoutByteEvidence({ root, scan, evidence }),\n evidence,\n });\n if (composed.status !== 'complete')\n throw new Error(\n `Workspace cannot be composed: ${composed.diagnostics.map((item) => `${item.code} ${item.path}: ${item.message}`).join('; ')}`,\n );\n return composed;\n}\nasync function readHead(api: CodeFirstApi, deadline: number, print: (line: string) => void): Promise<Head> {\n for (;;) {\n const response = await api.head();\n if (response.status === 200) return response.data as Head;\n if (response.status !== 409) throw new Error(`Unable to read model head (HTTP ${response.status})`);\n const revision = (response.data as ApplyingHead).revisionId;\n if (Date.now() >= deadline) throw new Error(`Apply r${revision} is in progress; retry pull shortly`);\n print(`Apply r${revision} in progress; retry shortly.`);\n await pause();\n }\n}\n\n/** Why a resource kept its local content, in the notice vocabulary the commands already print. */\nconst PRESERVE_NOTICE: Record<PreserveReason, Notice['status'] | undefined> = {\n unmaterialized: 'unmaterialized',\n 'kept-local': 'kept local',\n 'kept-local-edits': 'kept local edits',\n conflict: 'conflict',\n 'local-deletion-pending': 'kept local',\n 'pull-needed': 'pull needed',\n 'protected-descendant': 'conflict',\n // The one `kept-in-place` notice names the folder and everything that holds it; this is silent.\n 'folder-held': undefined,\n 'unsupported-evidence': 'conflict',\n 'post-submission-change': 'kept local edits',\n // A receipt says nothing about a resource it never carried; that is not news for the author.\n 'deferred-receipt': undefined,\n 'shared-container-relocation': 'kept local',\n 'shared-container-sibling': 'kept local',\n 'unsuccessful-outcome': undefined,\n 'missing-outcome': undefined,\n};\n\nfunction materializationPath(item: Extract<PhysicalMaterialization, { mode: 'set' }>): string {\n return item.codec === 'grouped' ? item.destination.file : item.bytes;\n}\n\nfunction preservePath(item: Extract<PhysicalMaterialization, { mode: 'preserve' }>): string {\n for (const contributor of item.contributors) {\n if (contributor.kind === 'grouped' || contributor.kind === 'grouped-navigation')\n return contributor.selector.file;\n if (contributor.kind === 'raw') return contributor.bytes ?? rawBytesPath(contributor.selector.sidecar);\n }\n return item.documentKey ?? 'workspace';\n}\n\nfunction planNotices(result: LayoutPlanOutcome): Notice[] {\n const notices: Notice[] = [];\n for (const item of result.materializations) {\n if (item.mode === 'set')\n notices.push({\n status: item.placement === 'insert-authoritative' ? 'new' : 'updated',\n key: item.documentKey,\n path: materializationPath(item),\n });\n else if (item.mode === 'preserve') {\n const status = PRESERVE_NOTICE[item.reason];\n if (status)\n notices.push({\n status,\n ...(item.documentKey ? { key: item.documentKey } : {}),\n path: preservePath(item),\n });\n }\n }\n for (const removal of result.deletes.json)\n notices.push({ status: 'deleted', key: removal.documentKeys[0], path: removal.path });\n for (const notice of result.notices) notices.push({ ...notice });\n return notices;\n}\n\n/** Name the resources that kept their old baseline, and once why the rescan could not prove them. */\nfunction reportUnverified(result: LayoutPlanOutcome, print: (line: string) => void): void {\n if (!result.unverifiedDocumentKeys.length) return;\n print(\n `warning: unverified-readback: ${result.unverifiedDocumentKeys.length} resources kept their previous baseline (${result.unverifiedDocumentKeys.slice(0, 5).join(', ')}${result.unverifiedDocumentKeys.length > 5 ? ', \u2026' : ''})`,\n );\n for (const item of result.verificationDiagnostics.slice(0, 5))\n print(`warning: ${item.code}: ${item.path}: ${item.message}`);\n}\n\n/** Per-resource composition problems: the command carried on, so they print as plain warnings. */\nfunction reportCompositionWarnings(\n warnings: readonly { code: string; path: string; message: string }[],\n print: (line: string) => void,\n): void {\n for (const item of warnings) print(`warning: ${item.code}: ${item.path}: ${item.message}`);\n}\n\n/** Temporary files the writer could not remove. The workspace is already saved and correct. */\nfunction reportCleanup(result: LayoutPlanOutcome, print: (line: string) => void): void {\n for (const warning of result.cleanupWarnings ?? []) print(`warning: cleanup: ${warning}`);\n}\n\n/**\n * Name every receipt the state reader set aside. The workspace stays usable; what it loses is the\n * receipt's own evidence, so a create that receipt assigned can reach the next plan as a create.\n */\nfunction reportUnreadableReceipts(state: State, print: (line: string) => void): void {\n for (const planId of Object.keys(state.layout.unreadableReceipts ?? {}).sort())\n print(\n `warning: the saved receipt for plan p${planId} could not be read and was set aside; ` +\n 'read the next plan before applying it, in case it creates a resource that apply already made',\n );\n}\n\n/**\n * Name the head resources the workspace does not hold. A command sends the baseline it has, so a\n * workspace that could not materialize everything otherwise reports no drift at all. A pull counts\n * them against the head it read; a plan takes the count the server computed against its own read.\n */\nfunction reportBehindHead(behind: number, print: (line: string) => void): void {\n if (behind > 0)\n print(`warning: workspace is behind head: ${behind} resources not materialized locally; run farseer code pull`);\n}\n\nfunction requireComplete(result: Awaited<ReturnType<typeof materializeLayoutPlan>>): LayoutPlanOutcome {\n if (result.status === 'blocked')\n throw new Error(\n `Workspace cannot be updated: ${result.diagnostics.map((item) => `${item.code} ${item.path}: ${item.message}`).join('; ')}`,\n );\n return result;\n}\n\n/** Fast-forward one workspace to the head the caller just read, and report every resource it touched. */\nasync function materializeHead(\n api: CodeFirstApi,\n root: string,\n head: Head,\n force: boolean,\n print: (line: string) => void,\n verbose = false,\n): Promise<number> {\n const result = requireComplete(\n await materializeLayoutPlan({ root, head, source: { kind: 'checkout', force }, api }),\n );\n const notices = planNotices(result);\n renderNotices(notices).forEach((line) => print(line));\n reportCompositionWarnings(result.compositionWarnings, print);\n reportUnverified(result, print);\n reportCleanup(result, print);\n // The head's diagnostics are tenant data the pull did not cause; only --verbose prints them.\n if (verbose) head.diagnostics.forEach((d) => print(`warning: ${d.code}: ${d.message}`));\n const saved = loadState(root);\n reportUnreadableReceipts(saved, print);\n reportBehindHead(Object.entries(head.manifest).filter(([key, hash]) => saved.baseline[key] !== hash).length, print);\n print(`Model pulled at r${head.revisionId}: ${Object.keys(head.manifest).length} resources.`);\n if (layoutExitCode(notices)) process.exitCode = 1;\n return notices.filter((notice) => ['new', 'updated', 'deleted'].includes(notice.status)).length;\n}\n\n/**\n * Create `<directory>/<tenant>/` and fill it with the head. The head is read before anything exists.\n * The directory and the stored identity come from the resolved target. `typedTenant` is the tenant\n * the command named, if it named one: it must be the resolved tenant and no other, so a saved\n * mapping can never redirect a named checkout to a different model. With no tenant typed, the\n * command asked for `FARSEER_TENANT`'s tenant and there is nothing to cross-check.\n */\nexport async function checkoutModel(\n target: TenantSession,\n typedTenant: string | undefined,\n directory: string,\n seconds: number,\n print = console.log,\n options: { verbose?: boolean } = {},\n): Promise<number> {\n if (typedTenant !== undefined && target.tenant !== typedTenant)\n throw new Error(\n `Refusing to check out: the command named the tenant ${typedTenant} but the resolved target is ${target.tenant}`,\n );\n const api = new CodeFirstApi(target);\n const head = await readHead(api, Date.now() + seconds * 1000, print);\n const root = createCodeWorkspace(directory, target.tenant, {\n organisation: target.organisation,\n baseUrl: api.baseUrl(),\n });\n return withWorkspaceLock(root, 'code checkout', async () => {\n print(`Checked out ${target.tenant} into ${root}`);\n return materializeHead(api, root, head, false, print, options.verbose);\n });\n}\n\n/** How many plans that were created but never applied stay applicable from this workspace. */\nexport const KEPT_UNAPPLIED_DRAFTS = 3;\n\n/**\n * Drop the drafts this workspace no longer needs: one whose receipt is written, and the oldest of\n * those never applied beyond the newest few. Each draft holds the whole submitted workspace, and an\n * author who re-plans ten times should not pay for ten copies. A draft that is `applying` is never\n * dropped. Returns whether anything was dropped, and the never-applied plans among the dropped ones.\n */\nexport function pruneDrafts(state: State): { changed: boolean; unapplied: string[] } {\n const before = Object.keys(state.layout.receipts).length;\n for (const [planId, draft] of Object.entries(state.layout.receipts))\n if (draft.receipt && !draft.applying) delete state.layout.receipts[planId];\n const unapplied = Object.entries(state.layout.receipts)\n .filter(([, draft]) => !draft.applying && !draft.receipt)\n .map(([planId]) => planId)\n .sort((left, right) => Number(right) - Number(left));\n const dropped = unapplied.slice(KEPT_UNAPPLIED_DRAFTS).reverse();\n for (const planId of dropped) delete state.layout.receipts[planId];\n return { changed: Object.keys(state.layout.receipts).length !== before, unapplied: dropped };\n}\n\n/**\n * The line that names the never-applied plans a prune dropped, so a later `code apply` of one of\n * them is not a surprise. A dropped draft whose receipt is written is done and goes unannounced.\n */\nfunction reportDroppedDrafts(unapplied: readonly string[], print: (line: string) => void): void {\n if (!unapplied.length) return;\n const plans = unapplied.map((planId) => `p${planId}`).join(', ');\n print(\n `Dropped the saved plan${unapplied.length > 1 ? 's' : ''} ${plans}: only the newest ` +\n `${KEPT_UNAPPLIED_DRAFTS} unapplied plans stay applicable.`,\n );\n}\n\n/** Every command starts by shedding the drafts it will never read again, before it loads anything else. */\nfunction pruneSavedDrafts(root: string, print: (line: string) => void): void {\n const current = loadState(root);\n const pruned = pruneDrafts(current);\n if (pruned.changed) saveState(root, current);\n reportDroppedDrafts(pruned.unapplied, print);\n}\n\n/**\n * Save an attempt's receipt in its draft before any document changes. The draft stays `applying`\n * until the receipt is written, so a pull or a retry that finds it still writes it first.\n */\nfunction storeReceipt(root: string, planId: string, receipt: Receipt): void {\n const stored = loadState(root);\n // The receipt is the server's answer, so no request of this draft is left running.\n const draft = { ...stored.layout.receipts[planId], receipt, revisionId: receipt.revisionId, applying: true };\n delete draft.unanswered;\n stored.layout.receipts[planId] = draft;\n saveState(root, stored);\n}\n\n/** Write one saved receipt into the workspace against the head the caller read, and report it. */\nasync function materializeReceipt(\n api: CodeFirstApi,\n root: string,\n planId: string,\n head: Head,\n print: (line: string) => void,\n): Promise<Notice[]> {\n const result = requireComplete(\n await materializeLayoutPlan({ root, head, source: { kind: 'receipt', planId }, api }),\n );\n // The draft existed to bind this receipt to the files it was planned from; written, it is done.\n const written = loadState(root);\n delete written.layout.receipts[planId];\n saveState(root, written);\n const notices = planNotices(result);\n renderNotices(notices).forEach((line) => print(line));\n reportCompositionWarnings(result.compositionWarnings, print);\n reportUnverified(result, print);\n reportCleanup(result, print);\n return notices;\n}\n\n/**\n * Write the receipt of every apply this workspace has not written yet, before the pull: one whose\n * response never arrived, and one saved but not written. The head holds that apply's creates, and\n * only its receipt proves which local file each of them is; without it the pull would place them a\n * second time. `GET \u2026/attempt` only observes, so this never resumes an attempt. A 404 from it proves\n * the plan was never admitted only when every apply request of the draft got the server's answer,\n * the same evidence `releaseIfAbsent` clears on in `code apply`: the `applying` guard is cleared and\n * the draft stays, still applicable. A draft whose request went unanswered (`unanswered`) may still\n * be admitted by that request, so it keeps the guard and the pull stops. Any other answer, or a\n * failed read, keeps the guard. Returns whether a receipt needs the author.\n */\nasync function writeUnwrittenReceipts(\n api: CodeFirstApi,\n root: string,\n head: Head,\n print: (line: string) => void,\n): Promise<boolean> {\n let attention = false;\n for (const [planId, draft] of Object.entries(loadState(root).layout.receipts).sort()) {\n if (!draft.applying) continue;\n let receipt = draft.receipt;\n if (!receipt) {\n const observed = await api.attempt(planId);\n if (observed.status === 404 && draft.unanswered)\n throw new Error(`Cannot pull yet: ${unansweredApply(planId)}`);\n // No attempt exists and no request can still create one, so the guard has nothing to protect.\n if (observed.status === 404) {\n updateDraft(root, planId, (current) => {\n current.applying = false;\n });\n print(`Plan p${planId} was never applied; it stays applicable with farseer code apply p${planId}`);\n continue;\n }\n if (observed.status !== 200)\n throw new Error(`Apply p${planId} is still in progress; resume it with farseer code apply p${planId}`);\n receipt = observed.data as Receipt;\n storeReceipt(root, planId, receipt);\n }\n print(`Writing the receipt of plan p${planId}: r${receipt.revisionId} (${receipt.status}).`);\n renderReceipt(receipt, [...draft.submission.operations]).forEach((line) => print(line));\n const notices = await materializeReceipt(api, root, planId, head, print);\n if (layoutExitCode(notices, receipt.status)) attention = true;\n }\n return attention;\n}\n\n/** `code pull`, holding the workspace lock. */\nexport async function pullModel(\n workspace: WorkspaceCommand,\n force: boolean,\n seconds: number,\n print: (line: string) => void = console.log,\n options: { verbose?: boolean } = {},\n): Promise<number> {\n return withWorkspaceLock(workspace.root, 'code pull', () =>\n pullWorkspace(workspace, force, seconds, print, options),\n );\n}\n\nasync function pullWorkspace(\n workspace: WorkspaceCommand,\n force: boolean,\n seconds: number,\n print: (line: string) => void,\n options: { verbose?: boolean },\n): Promise<number> {\n const api = workspaceApi(workspace);\n pruneSavedDrafts(workspace.root, print);\n const head = await readHead(api, Date.now() + seconds * 1000, print);\n const attention = await writeUnwrittenReceipts(api, workspace.root, head, print);\n const written = await materializeHead(api, workspace.root, head, force, print, options.verbose);\n if (attention) process.exitCode = 1;\n return written;\n}\n\n/** Upload every referenced blob whose descriptor the workspace evidence does not already know. */\nasync function uploadChangedBytes(\n api: Pick<BlobApi, 'uploadBlob'>,\n root: string,\n state: State,\n current: CompleteComposition,\n): Promise<void> {\n const known = new Set(\n state.layout.evidence.binaryRoutes.flatMap((route) => (route.byteHash ? [route.byteHash] : [])),\n );\n const referenced = new Set(\n [...current.binary.rawObservations, ...current.binary.attachmentObservations].flatMap((observation) =>\n observation.bytes ? [observation.bytes] : [],\n ),\n );\n const sent = new Set<string>();\n for (const fact of current.byteFacts) {\n if (!referenced.has(fact.path) || fact.state !== 'present') continue;\n if (known.has(canonicalFragmentHash(fact.content as unknown as Json)) || sent.has(fact.content.sha256))\n continue;\n if (fact.content.size > BLOB_UPLOAD_LIMIT)\n throw new Error(`Changed file ${fact.path} exceeds the 64 MiB upload limit`);\n const source = resolveLayoutPath(root, fact.path);\n if (!sameBytes(hashFile(source), fact.content))\n throw new Error(`Local bytes changed before upload: ${fact.path}`);\n await api.uploadBlob(fact.content.sha256, fs.createReadStream(source));\n sent.add(fact.content.sha256);\n }\n}\n\ntype PlanOptions = { verbose?: boolean; json?: boolean; note?: (line: string) => void };\n\n/**\n * `code plan`, holding the workspace lock. With `json`, `print` receives the plan response exactly\n * as the server returned it and nothing else, so stdout can be parsed; every other line goes to\n * `note` (stderr by default).\n */\nexport async function planModel(\n workspace: WorkspaceCommand,\n seconds: number,\n print: (line: string) => void = console.log,\n options: PlanOptions = {},\n): Promise<void> {\n return withWorkspaceLock(workspace.root, 'code plan', () => planWorkspace(workspace, seconds, print, options));\n}\n\nasync function planWorkspace(\n workspace: WorkspaceCommand,\n seconds: number,\n print: (line: string) => void,\n options: PlanOptions,\n): Promise<void> {\n const api = workspaceApi(workspace);\n const note = options.json ? (options.note ?? console.error) : print;\n pruneSavedDrafts(workspace.root, note);\n const root = workspace.root,\n readText = stateText(root),\n state = parseState(readText);\n const current = composeWorkspace(root, state);\n reportUnreadableReceipts(state, note);\n reportCompositionWarnings(current.warnings, note);\n if (!current.documents.length && !Object.keys(state.baseline).length)\n throw new Error('The workspace holds no model; run farseer code pull first');\n // A deleted tree or a `git clean -fd` (which keeps the ignored .fscode/) would plan to delete everything.\n if (!current.documents.length)\n throw new Error(\n `The workspace holds no model files, but its baseline has ${Object.keys(state.baseline).length} ` +\n 'resources, so a plan would delete them all; restore the files with farseer code pull --force',\n );\n await uploadChangedBytes(api, root, state, current);\n refuseUnwrittenReceipts(state);\n const deadline = Date.now() + seconds * 1000;\n let response = await api.plan(current.documents, state.baseline);\n while (response.status === 409 && Date.now() < deadline) {\n note(`Apply r${(response.data as ApplyingHead).revisionId} in progress; retry shortly.`);\n await pause();\n response = await api.plan(current.documents, state.baseline);\n }\n if (response.status === 409) throw new Error('Apply in progress; retry farseer code plan shortly');\n const planned = planOf(response.data);\n if (planned && planned.documentKeys?.length === current.documents.length)\n validateDocumentKeys(current.documents, planned.documentKeys, true);\n // The server holds the plan from here on, so its draft is saved before anything else can fail.\n let dropped: string[] = [];\n if (planned?.planId) {\n const submission = bindLayoutReceiptSubmission({\n planId: planned.planId,\n plan: planned,\n captured: captureLayoutSubmissionComposition(current),\n });\n const saved = parseState(stateText(root));\n saved.layout.receipts[planned.planId] = { submission };\n dropped = pruneDrafts(saved).unapplied;\n saveState(root, saved);\n } else saveLearnedByteHashes(root, readText);\n if (options.json) print(JSON.stringify(response.body, null, 2));\n if (!planned) throw new Error(planRefusal(response.status, response.data));\n if (!options.json)\n renderPlan(planned, { verbose: options.verbose, files: submittedDocumentFiles(current.sources) }).forEach(\n (line) => print(line),\n );\n reportBehindHead(planned.behindHead ?? 0, note);\n if (planned.planId)\n note(`Plan p${planned.planId} created against r${planned.observedRevisionId ?? state.revisionId}.`);\n reportDroppedDrafts(dropped, note);\n if (!planned.applicable || response.status === 400) process.exitCode = 1;\n}\n\n/** A plan's expiry as the server wrote it (ISO 8601); an unreadable date is left out. */\nconst expiryText = (date: Date) => (Number.isNaN(date.getTime()) ? undefined : date.toISOString());\n\n/** A POST plans answer as a plan (a 400 one carries a top-level `code`); a plain error is none. */\nfunction planOf(body: unknown): Plan | undefined {\n return body !== null && typeof body === 'object' && 'operations' in body ? (body as Plan) : undefined;\n}\n/** Why a POST plans answer holds no plan: the server's `{code, message}` error, or what it sent instead. */\nfunction planRefusal(status: number, body: unknown): string {\n const { code, message } = (body !== null && typeof body === 'object' ? body : {}) as Partial<ErrorResponse>;\n if (typeof code !== 'string') return `Invalid plan response (HTTP ${status})`;\n return `The server refused the plan (HTTP ${status}, ${code})${typeof message === 'string' ? `: ${message}` : ''}`;\n}\n\n/** `code apply`, holding the workspace lock. */\nexport async function applyModel(\n workspace: WorkspaceCommand,\n rawId: string,\n seconds: number,\n print: (line: string) => void = console.log,\n): Promise<void> {\n return withWorkspaceLock(workspace.root, `code apply ${rawId}`, () =>\n applyWorkspace(workspace, rawId, seconds, print),\n );\n}\n\nasync function applyWorkspace(\n workspace: WorkspaceCommand,\n rawId: string,\n seconds: number,\n print: (line: string) => void,\n): Promise<void> {\n // `workspace` is the one this command resolved, together with the state read at that moment.\n // Never carry it across commands: the state on disk moves with every write below.\n const planId = rawId.replace(/^p/, '');\n if (!/^[1-9][0-9]*$/.test(planId)) throw new Error('Expected a plan id such as p123');\n const api = workspaceApi(workspace);\n pruneSavedDrafts(workspace.root, print);\n const root = workspace.root;\n const initial = loadState(root),\n draft = initial.layout.receipts[planId];\n reportUnreadableReceipts(initial, print);\n if (!draft) {\n const unreadable = layoutReceiptDrafts(initial).find(([id, saved]) => id === planId && saved.quarantined);\n throw new Error(\n !unreadable\n ? 'This plan was not created in this workspace, its receipt is already written, or it was dropped ' +\n `as older than the newest ${KEPT_UNAPPLIED_DRAFTS} unapplied plans; create a new plan here`\n : unreadable[1].applying\n ? quarantinedApplyAdvice(planId)\n : `The saved receipt for plan p${planId} could not be read; run farseer code plan and apply the new plan`,\n );\n }\n const reportExpired = (expiresAt?: Date) => {\n const on = expiresAt && expiryText(expiresAt);\n print(`Plan p${planId} expired${on ? ` on ${on}` : ''}; run farseer code plan again.`);\n process.exitCode = 1;\n };\n let absentAttempt = false;\n if (draft.applying) {\n // Clear a stale admission guard only after the server proves no attempt exists.\n // Transport/auth errors and existing attempts remain fail-closed.\n const observed = await api.attempt(planId);\n if (observed.status === 404) {\n absentAttempt = true;\n } else if (observed.status !== 200 && observed.status !== 202) {\n throw new Error(\n `Unable to inspect saved attempt (HTTP ${observed.status}); retry farseer code apply p${planId}`,\n );\n }\n }\n let storedPlan: Plan;\n try {\n storedPlan = (await api.getPlan(planId)).data;\n } catch (error) {\n // A 404 is proof only when no earlier apply request of this draft can still be running.\n if (absentAttempt && !draft.unanswered)\n updateDraft(root, planId, (current) => {\n current.applying = false;\n });\n throw error;\n }\n // Checked before the guard and the POST: a plan this workspace did not create must never run.\n if (!sameStoredPlan(storedPlan, draft.submission))\n throw new Error(\n `Plan p${planId} on ${workspace.state.baseUrl} is not the plan this workspace created ` +\n '(its documents, operations or handles differ); run farseer code plan and apply the new plan',\n );\n if (storedPlan.expired) {\n // The server proved no attempt exists, and an expired plan can never admit one.\n if (absentAttempt)\n updateDraft(root, planId, (current) => {\n current.applying = false;\n delete current.unanswered;\n });\n reportExpired(storedPlan.expiresAt);\n return;\n }\n // The request counts as unanswered from before it is sent until the server answers it.\n if (\n !updateDraft(root, planId, (current) => {\n current.applying = true;\n current.unanswered = true;\n })\n )\n throw new Error(`The saved draft of plan p${planId} was removed by another command; run farseer code pull`);\n const deadline = Date.now() + seconds * 1000;\n /**\n * After a POST that is over on the server side: no request is left running, so the guard is\n * cleared once `GET \u2026/attempt` proves no attempt exists, and kept otherwise (or when the read fails).\n */\n const releaseIfAbsent = async () => {\n let observed;\n try {\n observed = await api.attempt(planId);\n } catch {\n observed = undefined;\n }\n updateDraft(root, planId, (current) => {\n delete current.unanswered;\n if (observed?.status === 404) current.applying = false;\n });\n };\n /**\n * A POST that may still be running on the server keeps the guard: admission can go on there and\n * assign ids nobody would record. Posting the same apply again is idempotent, so that is the way on.\n */\n const post = () =>\n api.apply(planId).catch(async (error: unknown) => {\n if (!requestSettled(error))\n throw new Error(\n `${error instanceof Error ? error.message : String(error)}: ${unansweredApply(planId)}`,\n { cause: error },\n );\n await releaseIfAbsent();\n throw error;\n });\n let response = await post();\n // Another apply holds the head, or the head moved twice during admission: both pass, so post again.\n while (\n response.status === 409 &&\n 'code' in response.data &&\n (response.data.code === 'apply-in-progress' || response.data.code === 'admission-conflict') &&\n Date.now() < deadline\n ) {\n print(\n response.data.code === 'apply-in-progress'\n ? `Apply r${(response.data as ApplyingHead).revisionId} in progress; retry shortly.`\n : `The head changed while plan p${planId} was being admitted; retry shortly.`,\n );\n await pause();\n response = await post();\n }\n if ('code' in response.data && response.data.code === 'admission-conflict') {\n // Nothing was admitted; the guard is cleared once the server confirms no attempt exists.\n await releaseIfAbsent();\n print(`The head kept changing while plan p${planId} was being admitted. Retry: farseer code apply p${planId}`);\n process.exitCode = 1;\n return;\n }\n while (response.status === 202 && Date.now() < deadline) {\n const pending = response.data as Pending;\n updateDraft(root, planId, (current) => {\n current.revisionId = pending.revisionId;\n delete current.unanswered;\n });\n print(`Pending r${pending.revisionId}; waiting for attempt receipt.`);\n await pause();\n // v1 has no background finalizer: an idempotent POST consumes new engine results and resumes stages.\n response = await post();\n }\n if ('code' in response.data && response.data.code === 'plan-expired') {\n // Expiry raced GET/POST. The server proves no attempt was admitted: clear only\n // the durable pre-POST guard, without consuming a receipt or altering model/baseline data.\n updateDraft(root, planId, (current) => {\n current.applying = false;\n delete current.unanswered;\n });\n reportExpired(response.data.expiresAt);\n return;\n }\n if (response.status === 202 || response.status === 409) {\n // The server answered: an attempt holds this plan (202), or another apply holds the head (409).\n const answered = response.data as Pending | ApplyingHead;\n updateDraft(root, planId, (current) => {\n if (response.status === 202) current.revisionId = answered.revisionId;\n delete current.unanswered;\n });\n print(\n `Revision r${answered.revisionId} is ${response.status === 202 ? 'pending' : 'applying'}. Resume: farseer code apply p${planId}`,\n );\n process.exitCode = 1;\n return;\n }\n if (response.status !== 200) {\n await releaseIfAbsent();\n throw new Error(`Apply failed (HTTP ${response.status})`);\n }\n const receipt = response.data as Receipt;\n storeReceipt(root, planId, receipt);\n let head: Head | undefined;\n try {\n head = await readHead(api, deadline, print);\n } catch (error) {\n print(\n `Post-apply readback unavailable: ${(error as Error).message}; the next farseer code pull writes the receipt`,\n );\n }\n renderReceipt(receipt, storedPlan.operations).forEach((line) => print(line));\n const notices = head ? await materializeReceipt(api, root, planId, head, print) : [];\n print(`Tenant '${workspace.target.tenant}' now at r${receipt.revisionId} (${receipt.status})`);\n if (!head || layoutExitCode(notices, receipt.status)) process.exitCode = 1;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AAGpB,iBAA6C;AAC7C,wBAAqE;AACrE,uBAAgE;AAChE,2BAAoG;AACpG,wBAAsC;AACtC,yBAA6B;AAC7B,4BAMO;AACP,2BAMO;AACP,wBAAiF;AACjF,oBAAyE;AAazE,uBAA4E;AAC5E,2BAAkC;AAClC,2BAAwD;AAUxD,MAAM,QAAQ,MAAM,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,GAAI,CAAC;AACrE,SAAS,YAAY,OAAuB;AAC/C,QAAM,UAAU,OAAO,KAAK;AAC5B,MAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,KAAK,UAAU;AACtD,UAAM,IAAI,MAAM,2CAA2C;AAC/D,SAAO;AACX;AACA,SAAS,UAAU,MAAqB;AACpC,MAAI,CAAC,GAAG,eAAW,gCAAc,MAAM,2BAAU,CAAC;AAC9C,UAAM,IAAI,MAAM,8DAA8D;AAClF,aAAO,iCAAW,6BAAU,IAAI,CAAC;AACrC;AAOA,SAAS,YAAY,MAAc,QAAgB,QAAsD;AACrG,QAAM,UAAU,UAAU,IAAI;AAC9B,QAAM,QAAQ,QAAQ,OAAO,SAAS,MAAM;AAC5C,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,KAAK;AACZ,kCAAU,MAAM,OAAO;AACvB,SAAO;AACX;AAGA,S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strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var workspace_exports = {};
|
|
30
|
+
__export(workspace_exports, {
|
|
31
|
+
STATE_DIR: () => import_workspaceRoot2.STATE_DIR,
|
|
32
|
+
STATE_FILE: () => import_workspaceRoot2.STATE_FILE,
|
|
33
|
+
atomicReplaceText: () => atomicReplaceText,
|
|
34
|
+
saveLearnedByteHashes: () => saveLearnedByteHashes,
|
|
35
|
+
saveState: () => saveState,
|
|
36
|
+
stageDownloadedFile: () => stageDownloadedFile,
|
|
37
|
+
stageText: () => stageText,
|
|
38
|
+
stageVerifiedFile: () => stageVerifiedFile,
|
|
39
|
+
workspacePath: () => workspacePath
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(workspace_exports);
|
|
42
|
+
var fs = __toESM(require("fs"));
|
|
43
|
+
var path = __toESM(require("path"));
|
|
44
|
+
var import_crypto = require("crypto");
|
|
45
|
+
var import_stream = require("stream");
|
|
46
|
+
var import_promises = require("stream/promises");
|
|
47
|
+
var import_documents = require("./documents");
|
|
48
|
+
var import_byteHashes = require("./byteHashes");
|
|
49
|
+
var import_binaryDisk = require("./binaryDisk");
|
|
50
|
+
var import_workspaceRoot = require("./workspaceRoot");
|
|
51
|
+
var import_workspaceRoot2 = require("./workspaceRoot");
|
|
52
|
+
function rejectSymlink(file) {
|
|
53
|
+
try {
|
|
54
|
+
if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`Refusing symlink: ${file}`);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error.code !== "ENOENT") throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function workspacePath(root, relative) {
|
|
60
|
+
if (relative.includes("\\") || [...relative].some((character) => character.charCodeAt(0) < 32) || relative.split("/").some((part) => !part || part === "." || part === ".."))
|
|
61
|
+
throw new Error(`Unsafe workspace path: ${JSON.stringify(relative)}`);
|
|
62
|
+
const resolved = path.resolve(root, relative);
|
|
63
|
+
const rel = path.relative(path.resolve(root), resolved);
|
|
64
|
+
if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error("Workspace path escapes tenant directory");
|
|
65
|
+
let current = path.resolve(root);
|
|
66
|
+
rejectSymlink(current);
|
|
67
|
+
for (const part of rel.split(path.sep)) {
|
|
68
|
+
current = path.join(current, part);
|
|
69
|
+
rejectSymlink(current);
|
|
70
|
+
}
|
|
71
|
+
return resolved;
|
|
72
|
+
}
|
|
73
|
+
function removeOwnedTemporary(temporary) {
|
|
74
|
+
if (!temporary) return;
|
|
75
|
+
try {
|
|
76
|
+
const stat = fs.lstatSync(temporary.path);
|
|
77
|
+
if (stat.dev === temporary.dev && stat.ino === temporary.ino) fs.unlinkSync(temporary.path);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error.code !== "ENOENT") throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function assertOwnedTemporary(temporary) {
|
|
83
|
+
if (!temporary) throw new Error("Temporary file is no longer owned");
|
|
84
|
+
const stat = fs.lstatSync(temporary.path);
|
|
85
|
+
if (stat.dev !== temporary.dev || stat.ino !== temporary.ino)
|
|
86
|
+
throw new Error(`Temporary file changed before replacement: ${temporary.path}`);
|
|
87
|
+
}
|
|
88
|
+
function existingMode(file) {
|
|
89
|
+
try {
|
|
90
|
+
const stat = fs.lstatSync(file);
|
|
91
|
+
return stat.isFile() ? stat.mode & 511 : void 0;
|
|
92
|
+
} catch {
|
|
93
|
+
return void 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function atomicReplaceText(file, content) {
|
|
97
|
+
const temporary = `${file}.tmp-${(0, import_crypto.randomUUID)()}`;
|
|
98
|
+
let descriptor;
|
|
99
|
+
let owned;
|
|
100
|
+
try {
|
|
101
|
+
descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 384);
|
|
102
|
+
const stat = fs.fstatSync(descriptor);
|
|
103
|
+
owned = { path: temporary, dev: stat.dev, ino: stat.ino };
|
|
104
|
+
const mode = existingMode(file);
|
|
105
|
+
if (mode !== void 0) fs.fchmodSync(descriptor, mode);
|
|
106
|
+
fs.writeFileSync(descriptor, content, { encoding: "utf8" });
|
|
107
|
+
fs.closeSync(descriptor);
|
|
108
|
+
descriptor = void 0;
|
|
109
|
+
assertOwnedTemporary(owned);
|
|
110
|
+
fs.renameSync(temporary, file);
|
|
111
|
+
owned = void 0;
|
|
112
|
+
} finally {
|
|
113
|
+
try {
|
|
114
|
+
if (descriptor !== void 0) fs.closeSync(descriptor);
|
|
115
|
+
} finally {
|
|
116
|
+
removeOwnedTemporary(owned);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function atomicWrite(file, content) {
|
|
121
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
122
|
+
atomicReplaceText(file, content);
|
|
123
|
+
}
|
|
124
|
+
function stageText(destination, content) {
|
|
125
|
+
const temporary = `${destination}.tmp-${(0, import_crypto.randomUUID)()}`;
|
|
126
|
+
let descriptor;
|
|
127
|
+
let owned;
|
|
128
|
+
try {
|
|
129
|
+
descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 384);
|
|
130
|
+
const stat = fs.fstatSync(descriptor);
|
|
131
|
+
owned = { path: temporary, dev: stat.dev, ino: stat.ino };
|
|
132
|
+
const mode = existingMode(destination);
|
|
133
|
+
if (mode !== void 0) fs.fchmodSync(descriptor, mode);
|
|
134
|
+
fs.writeFileSync(descriptor, content, { encoding: "utf8" });
|
|
135
|
+
fs.closeSync(descriptor);
|
|
136
|
+
descriptor = void 0;
|
|
137
|
+
} catch (error) {
|
|
138
|
+
try {
|
|
139
|
+
if (descriptor !== void 0) fs.closeSync(descriptor);
|
|
140
|
+
} finally {
|
|
141
|
+
removeOwnedTemporary(owned);
|
|
142
|
+
}
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
destination,
|
|
147
|
+
temporary,
|
|
148
|
+
commit(checkedDestination) {
|
|
149
|
+
if (checkedDestination !== destination)
|
|
150
|
+
throw new Error(`Staged destination changed before replacement: ${destination}`);
|
|
151
|
+
assertOwnedTemporary(owned);
|
|
152
|
+
fs.renameSync(temporary, checkedDestination);
|
|
153
|
+
owned = void 0;
|
|
154
|
+
},
|
|
155
|
+
cleanup() {
|
|
156
|
+
removeOwnedTemporary(owned);
|
|
157
|
+
owned = void 0;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function stageVerifiedFile(source, destination, content, label = destination) {
|
|
162
|
+
const temporary = `${destination}.tmp-${(0, import_crypto.randomUUID)()}`;
|
|
163
|
+
let input;
|
|
164
|
+
let output;
|
|
165
|
+
let owned;
|
|
166
|
+
try {
|
|
167
|
+
input = fs.openSync(source, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
168
|
+
const sourceStat = fs.fstatSync(input);
|
|
169
|
+
if (!sourceStat.isFile()) throw new Error(`Expected regular file: ${source}`);
|
|
170
|
+
output = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 384);
|
|
171
|
+
const stat = fs.fstatSync(output);
|
|
172
|
+
owned = { path: temporary, dev: stat.dev, ino: stat.ino };
|
|
173
|
+
const buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
174
|
+
let length;
|
|
175
|
+
while ((length = fs.readSync(input, buffer, 0, buffer.length, null)) > 0) {
|
|
176
|
+
let offset = 0;
|
|
177
|
+
while (offset < length) offset += fs.writeSync(output, buffer, offset, length - offset);
|
|
178
|
+
}
|
|
179
|
+
fs.closeSync(input);
|
|
180
|
+
input = void 0;
|
|
181
|
+
if (!(0, import_binaryDisk.sameBytes)((0, import_binaryDisk.hashFile)(temporary), content)) throw new Error(`Byte source changed while staging: ${label}`);
|
|
182
|
+
assertOwnedTemporary(owned);
|
|
183
|
+
fs.fchmodSync(output, existingMode(destination) ?? sourceStat.mode & 511);
|
|
184
|
+
fs.closeSync(output);
|
|
185
|
+
output = void 0;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
try {
|
|
188
|
+
if (input !== void 0) fs.closeSync(input);
|
|
189
|
+
} finally {
|
|
190
|
+
try {
|
|
191
|
+
if (output !== void 0) fs.closeSync(output);
|
|
192
|
+
} finally {
|
|
193
|
+
removeOwnedTemporary(owned);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
destination,
|
|
200
|
+
temporary,
|
|
201
|
+
commit(checkedDestination) {
|
|
202
|
+
if (checkedDestination !== destination)
|
|
203
|
+
throw new Error(`Staged destination changed before replacement: ${destination}`);
|
|
204
|
+
assertOwnedTemporary(owned);
|
|
205
|
+
fs.renameSync(temporary, checkedDestination);
|
|
206
|
+
owned = void 0;
|
|
207
|
+
},
|
|
208
|
+
cleanup() {
|
|
209
|
+
removeOwnedTemporary(owned);
|
|
210
|
+
owned = void 0;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
async function stageDownloadedFile(api, destination, content, onStaging) {
|
|
215
|
+
const temporary = `${destination}.tmp-${(0, import_crypto.randomUUID)()}`;
|
|
216
|
+
let owned;
|
|
217
|
+
let descriptor;
|
|
218
|
+
let stream;
|
|
219
|
+
try {
|
|
220
|
+
stream = await api.downloadBlob(content.sha256);
|
|
221
|
+
descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 384);
|
|
222
|
+
const stat = fs.fstatSync(descriptor);
|
|
223
|
+
owned = { path: temporary, dev: stat.dev, ino: stat.ino };
|
|
224
|
+
const mode = existingMode(destination);
|
|
225
|
+
if (mode !== void 0) fs.fchmodSync(descriptor, mode);
|
|
226
|
+
const output = fs.createWriteStream(temporary, { fd: descriptor, autoClose: true });
|
|
227
|
+
descriptor = void 0;
|
|
228
|
+
const hash = (0, import_crypto.createHash)("sha256");
|
|
229
|
+
let size = 0;
|
|
230
|
+
const source = stream;
|
|
231
|
+
stream = void 0;
|
|
232
|
+
onStaging?.(() => {
|
|
233
|
+
source.destroy();
|
|
234
|
+
output.destroy();
|
|
235
|
+
removeOwnedTemporary(owned);
|
|
236
|
+
});
|
|
237
|
+
await (0, import_promises.pipeline)(
|
|
238
|
+
source,
|
|
239
|
+
new import_stream.Transform({
|
|
240
|
+
transform(chunk, _encoding, done) {
|
|
241
|
+
size += chunk.length;
|
|
242
|
+
if (size > content.size) {
|
|
243
|
+
done(new Error("Blob download exceeds its declared size"));
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
hash.update(chunk);
|
|
247
|
+
done(null, chunk);
|
|
248
|
+
}
|
|
249
|
+
}),
|
|
250
|
+
output
|
|
251
|
+
);
|
|
252
|
+
if (size !== content.size || hash.digest("hex") !== content.sha256)
|
|
253
|
+
throw new Error("Blob download hash/size mismatch");
|
|
254
|
+
assertOwnedTemporary(owned);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
try {
|
|
257
|
+
if (stream && !stream.destroyed) stream.destroy();
|
|
258
|
+
if (descriptor !== void 0) fs.closeSync(descriptor);
|
|
259
|
+
} finally {
|
|
260
|
+
removeOwnedTemporary(owned);
|
|
261
|
+
}
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
destination,
|
|
266
|
+
temporary,
|
|
267
|
+
commit(checkedDestination) {
|
|
268
|
+
if (checkedDestination !== destination)
|
|
269
|
+
throw new Error(`Staged destination changed before replacement: ${destination}`);
|
|
270
|
+
assertOwnedTemporary(owned);
|
|
271
|
+
fs.renameSync(temporary, checkedDestination);
|
|
272
|
+
owned = void 0;
|
|
273
|
+
},
|
|
274
|
+
cleanup() {
|
|
275
|
+
removeOwnedTemporary(owned);
|
|
276
|
+
owned = void 0;
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
function saveState(root, state) {
|
|
281
|
+
atomicWrite(workspacePath(root, import_workspaceRoot.STATE_FILE), (0, import_documents.serializeState)(withByteHashes(root, state)));
|
|
282
|
+
}
|
|
283
|
+
function withByteHashes(root, state) {
|
|
284
|
+
if (!state.layout) return state;
|
|
285
|
+
const byteHashes = (0, import_byteHashes.persistableByteHashes)(root, state.layout.byteHashes);
|
|
286
|
+
const layout = { ...state.layout };
|
|
287
|
+
if (byteHashes) layout.byteHashes = byteHashes;
|
|
288
|
+
else delete layout.byteHashes;
|
|
289
|
+
return { ...state, layout };
|
|
290
|
+
}
|
|
291
|
+
function saveLearnedByteHashes(root, expectedStateText) {
|
|
292
|
+
if (!(0, import_byteHashes.byteHashesChanged)(root)) return;
|
|
293
|
+
const file = workspacePath(root, import_workspaceRoot.STATE_FILE);
|
|
294
|
+
const next = (0, import_documents.serializeState)(withByteHashes(root, (0, import_documents.parseState)(expectedStateText)));
|
|
295
|
+
if (next === expectedStateText || fs.readFileSync(file, "utf8") !== expectedStateText) return;
|
|
296
|
+
atomicWrite(file, next);
|
|
297
|
+
}
|
|
298
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
299
|
+
0 && (module.exports = {
|
|
300
|
+
STATE_DIR,
|
|
301
|
+
STATE_FILE,
|
|
302
|
+
atomicReplaceText,
|
|
303
|
+
saveLearnedByteHashes,
|
|
304
|
+
saveState,
|
|
305
|
+
stageDownloadedFile,
|
|
306
|
+
stageText,
|
|
307
|
+
stageVerifiedFile,
|
|
308
|
+
workspacePath
|
|
309
|
+
});
|
|
310
|
+
//# sourceMappingURL=workspace.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/services/codefirst/workspace.ts"],
|
|
4
|
+
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { createHash, randomUUID } from 'crypto';\nimport { Transform } from 'stream';\nimport { pipeline } from 'stream/promises';\nimport { parseState, serializeState } from './documents';\nimport { byteHashesChanged, persistableByteHashes } from './byteHashes';\nimport { BlobContent, State } from './types';\nimport { hashFile, sameBytes, type BlobApi } from './binaryDisk';\nimport { STATE_FILE } from './workspaceRoot';\n\nexport { STATE_DIR, STATE_FILE } from './workspaceRoot';\nfunction rejectSymlink(file: string): void {\n try {\n if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`Refusing symlink: ${file}`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n}\nexport function workspacePath(root: string, relative: string): string {\n if (\n relative.includes('\\\\') ||\n [...relative].some((character) => character.charCodeAt(0) < 0x20) ||\n relative.split('/').some((part) => !part || part === '.' || part === '..')\n )\n throw new Error(`Unsafe workspace path: ${JSON.stringify(relative)}`);\n const resolved = path.resolve(root, relative);\n const rel = path.relative(path.resolve(root), resolved);\n if (rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('Workspace path escapes tenant directory');\n let current = path.resolve(root);\n rejectSymlink(current);\n for (const part of rel.split(path.sep)) {\n current = path.join(current, part);\n rejectSymlink(current);\n }\n return resolved;\n}\ninterface OwnedTemporary {\n path: string;\n dev: number;\n ino: number;\n}\n\nfunction removeOwnedTemporary(temporary: OwnedTemporary | undefined): void {\n if (!temporary) return;\n try {\n const stat = fs.lstatSync(temporary.path);\n if (stat.dev === temporary.dev && stat.ino === temporary.ino) fs.unlinkSync(temporary.path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n}\n\nfunction assertOwnedTemporary(temporary: OwnedTemporary | undefined): asserts temporary is OwnedTemporary {\n if (!temporary) throw new Error('Temporary file is no longer owned');\n const stat = fs.lstatSync(temporary.path);\n if (stat.dev !== temporary.dev || stat.ino !== temporary.ino)\n throw new Error(`Temporary file changed before replacement: ${temporary.path}`);\n}\n\n/**\n * The permission bits of the regular file a replacement takes the place of, so a committed\n * executable bit survives a pull. A new file keeps the writer's own 0600.\n */\nfunction existingMode(file: string): number | undefined {\n try {\n const stat = fs.lstatSync(file);\n return stat.isFile() ? stat.mode & 0o777 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Atomically replace one text file without creating its parent directory. It keeps the file's mode. */\nexport function atomicReplaceText(file: string, content: string): void {\n const temporary = `${file}.tmp-${randomUUID()}`;\n let descriptor: number | undefined;\n let owned: OwnedTemporary | undefined;\n try {\n descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(descriptor);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const mode = existingMode(file);\n if (mode !== undefined) fs.fchmodSync(descriptor, mode);\n fs.writeFileSync(descriptor, content, { encoding: 'utf8' });\n fs.closeSync(descriptor);\n descriptor = undefined;\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, file);\n owned = undefined;\n } finally {\n try {\n if (descriptor !== undefined) fs.closeSync(descriptor);\n } finally {\n removeOwnedTemporary(owned);\n }\n }\n}\n\nfunction atomicWrite(file: string, content: string): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n atomicReplaceText(file, content);\n}\n\nexport interface StagedWorkspaceFile {\n destination: string;\n temporary: string;\n commit(destination: string): void;\n cleanup(): void;\n}\n\n/**\n * Write one text file into a destination-local temporary without replacing its destination. The\n * caller commits it later with a single rename, so nothing but that rename stands between this\n * file and another the same commit has to keep it beside.\n */\nexport function stageText(destination: string, content: string): StagedWorkspaceFile {\n const temporary = `${destination}.tmp-${randomUUID()}`;\n let descriptor: number | undefined;\n let owned: OwnedTemporary | undefined;\n try {\n descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(descriptor);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const mode = existingMode(destination);\n if (mode !== undefined) fs.fchmodSync(descriptor, mode);\n fs.writeFileSync(descriptor, content, { encoding: 'utf8' });\n fs.closeSync(descriptor);\n descriptor = undefined;\n } catch (error) {\n try {\n if (descriptor !== undefined) fs.closeSync(descriptor);\n } finally {\n removeOwnedTemporary(owned);\n }\n throw error;\n }\n return {\n destination,\n temporary,\n commit(checkedDestination) {\n if (checkedDestination !== destination)\n throw new Error(`Staged destination changed before replacement: ${destination}`);\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, checkedDestination);\n owned = undefined;\n },\n cleanup() {\n removeOwnedTemporary(owned);\n owned = undefined;\n },\n };\n}\n\n/** Copy and verify one destination-local temporary without replacing its destination. */\nexport function stageVerifiedFile(\n source: string,\n destination: string,\n content: BlobContent,\n label = destination,\n): StagedWorkspaceFile {\n const temporary = `${destination}.tmp-${randomUUID()}`;\n let input: number | undefined;\n let output: number | undefined;\n let owned: OwnedTemporary | undefined;\n try {\n input = fs.openSync(source, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);\n const sourceStat = fs.fstatSync(input);\n if (!sourceStat.isFile()) throw new Error(`Expected regular file: ${source}`);\n output = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(output);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const buffer = Buffer.allocUnsafe(1024 * 1024);\n let length: number;\n while ((length = fs.readSync(input, buffer, 0, buffer.length, null)) > 0) {\n let offset = 0;\n while (offset < length) offset += fs.writeSync(output, buffer, offset, length - offset);\n }\n fs.closeSync(input);\n input = undefined;\n if (!sameBytes(hashFile(temporary), content)) throw new Error(`Byte source changed while staging: ${label}`);\n assertOwnedTemporary(owned);\n fs.fchmodSync(output, existingMode(destination) ?? sourceStat.mode & 0o777);\n fs.closeSync(output);\n output = undefined;\n } catch (error) {\n try {\n if (input !== undefined) fs.closeSync(input);\n } finally {\n try {\n if (output !== undefined) fs.closeSync(output);\n } finally {\n removeOwnedTemporary(owned);\n }\n }\n throw error;\n }\n return {\n destination,\n temporary,\n commit(checkedDestination) {\n if (checkedDestination !== destination)\n throw new Error(`Staged destination changed before replacement: ${destination}`);\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, checkedDestination);\n owned = undefined;\n },\n cleanup() {\n removeOwnedTemporary(owned);\n owned = undefined;\n },\n };\n}\n\n/**\n * Stream one blob from the server into a destination-local temporary and verify its size and hash\n * on the way, without replacing the destination. Nothing goes through `os.tmpdir()`: a large tenant\n * would otherwise hold every missing blob there at once, in memory where `/tmp` is a tmpfs.\n * `onStaging` receives a function that stops the stream and removes the partial temporary as soon\n * as the temporary exists, so a Ctrl-C during the stream leaves nothing behind.\n */\nexport async function stageDownloadedFile(\n api: Pick<BlobApi, 'downloadBlob'>,\n destination: string,\n content: BlobContent,\n onStaging?: (abandon: () => void) => void,\n): Promise<StagedWorkspaceFile> {\n const temporary = `${destination}.tmp-${randomUUID()}`;\n let owned: OwnedTemporary | undefined;\n let descriptor: number | undefined;\n let stream: Awaited<ReturnType<BlobApi['downloadBlob']>> | undefined;\n try {\n stream = await api.downloadBlob(content.sha256);\n descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(descriptor);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const mode = existingMode(destination);\n if (mode !== undefined) fs.fchmodSync(descriptor, mode);\n const output = fs.createWriteStream(temporary, { fd: descriptor, autoClose: true });\n descriptor = undefined;\n const hash = createHash('sha256');\n let size = 0;\n const source = stream;\n stream = undefined;\n onStaging?.(() => {\n source.destroy();\n output.destroy();\n removeOwnedTemporary(owned);\n });\n await pipeline(\n source,\n new Transform({\n transform(chunk: Buffer, _encoding, done) {\n size += chunk.length;\n if (size > content.size) {\n done(new Error('Blob download exceeds its declared size'));\n return;\n }\n hash.update(chunk);\n done(null, chunk);\n },\n }),\n output,\n );\n if (size !== content.size || hash.digest('hex') !== content.sha256)\n throw new Error('Blob download hash/size mismatch');\n assertOwnedTemporary(owned);\n } catch (error) {\n try {\n if (stream && !stream.destroyed) stream.destroy();\n if (descriptor !== undefined) fs.closeSync(descriptor);\n } finally {\n removeOwnedTemporary(owned);\n }\n throw error;\n }\n return {\n destination,\n temporary,\n commit(checkedDestination) {\n if (checkedDestination !== destination)\n throw new Error(`Staged destination changed before replacement: ${destination}`);\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, checkedDestination);\n owned = undefined;\n },\n cleanup() {\n removeOwnedTemporary(owned);\n owned = undefined;\n },\n };\n}\n\n/** Write the state, carrying the byte-hash cache this command holds for the workspace. */\nexport function saveState(root: string, state: State): void {\n atomicWrite(workspacePath(root, STATE_FILE), serializeState(withByteHashes(root, state)));\n}\n\nfunction withByteHashes(root: string, state: State): State {\n if (!state.layout) return state;\n const byteHashes = persistableByteHashes(root, state.layout.byteHashes);\n const layout = { ...state.layout };\n if (byteHashes) layout.byteHashes = byteHashes;\n else delete layout.byteHashes;\n return { ...state, layout };\n}\n\n/**\n * Save only the byte-hash cache a read-only command learned, when the state on disk is still the\n * text the command read. The new text is built first, so the file is compared and replaced in one\n * short step: any other change to the state wins, and the cache is simply rebuilt later.\n */\nexport function saveLearnedByteHashes(root: string, expectedStateText: string): void {\n if (!byteHashesChanged(root)) return;\n const file = workspacePath(root, STATE_FILE);\n const next = serializeState(withByteHashes(root, parseState(expectedStateText)));\n if (next === expectedStateText || fs.readFileSync(file, 'utf8') !== expectedStateText) return;\n atomicWrite(file, next);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,oBAAuC;AACvC,oBAA0B;AAC1B,sBAAyB;AACzB,uBAA2C;AAC3C,wBAAyD;AAEzD,wBAAkD;AAClD,2BAA2B;AAE3B,IAAAA,wBAAsC;AACtC,SAAS,cAAc,MAAoB;AACvC,MAAI;AACA,QAAI,GAAG,UAAU,IAAI,EAAE,eAAe,EAAG,OAAM,IAAI,MAAM,qBAAqB,IAAI,EAAE;AAAA,EACxF,SAAS,OAAO;AACZ,QAAK,MAAgC,SAAS,SAAU,OAAM;AAAA,EAClE;AACJ;AACO,SAAS,cAAc,MAAc,UAA0B;AAClE,MACI,SAAS,SAAS,IAAI,KACtB,CAAC,GAAG,QAAQ,EAAE,KAAK,CAAC,cAAc,UAAU,WAAW,CAAC,IAAI,EAAI,KAChE,SAAS,MAAM,GAAG,EAAE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AC,CAAC;AAC5F;AAEA,SAAS,eAAe,MAAc,OAAqB;AACvD,MAAI,CAAC,MAAM,OAAQ,QAAO;AAC1B,QAAM,iBAAa,yCAAsB,MAAM,MAAM,OAAO,UAAU;AACtE,QAAM,SAAS,EAAE,GAAG,MAAM,OAAO;AACjC,MAAI,WAAY,QAAO,aAAa;AAAA,MAC/B,QAAO,OAAO;AACnB,SAAO,EAAE,GAAG,OAAO,OAAO;AAC9B;AAOO,SAAS,sBAAsB,MAAc,mBAAiC;AACjF,MAAI,KAAC,qCAAkB,IAAI,EAAG;AAC9B,QAAM,OAAO,cAAc,MAAM,+BAAU;AAC3C,QAAM,WAAO,iCAAe,eAAe,UAAM,6BAAW,iBAAiB,CAAC,CAAC;AAC/E,MAAI,SAAS,qBAAqB,GAAG,aAAa,MAAM,MAAM,MAAM,kBAAmB;AACvF,cAAY,MAAM,IAAI;AAC1B;",
|
|
6
|
+
"names": ["import_workspaceRoot"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var workspaceLock_exports = {};
|
|
30
|
+
__export(workspaceLock_exports, {
|
|
31
|
+
LOCK_FILE: () => LOCK_FILE,
|
|
32
|
+
acquireWorkspaceLock: () => acquireWorkspaceLock,
|
|
33
|
+
withWorkspaceLock: () => withWorkspaceLock
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(workspaceLock_exports);
|
|
36
|
+
var fs = __toESM(require("fs"));
|
|
37
|
+
var os = __toESM(require("os"));
|
|
38
|
+
var path = __toESM(require("path"));
|
|
39
|
+
var import_layoutReceipt = require("./layoutReceipt");
|
|
40
|
+
var import_workspaceRoot = require("./workspaceRoot");
|
|
41
|
+
const LOCK_FILE = `${import_workspaceRoot.STATE_DIR}/lock`;
|
|
42
|
+
const deleteAdvice = `If no such command is running, delete ${LOCK_FILE}.`;
|
|
43
|
+
function lockPath(root) {
|
|
44
|
+
return path.join(root, ...LOCK_FILE.split("/"));
|
|
45
|
+
}
|
|
46
|
+
function readLock(file) {
|
|
47
|
+
let text;
|
|
48
|
+
try {
|
|
49
|
+
text = fs.readFileSync(file, "utf8");
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error.code === "ENOENT") return void 0;
|
|
52
|
+
return { text: "" };
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const value = JSON.parse(text);
|
|
56
|
+
const valid = Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.hostname === "string" && typeof value.command === "string" && typeof value.startedAt === "string" && !Number.isNaN(Date.parse(value.startedAt));
|
|
57
|
+
return { text, holder: valid ? value : void 0 };
|
|
58
|
+
} catch {
|
|
59
|
+
return { text };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function running(pid) {
|
|
63
|
+
try {
|
|
64
|
+
process.kill(pid, 0);
|
|
65
|
+
return true;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
return error.code !== "ESRCH";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function startedLabel(startedAt) {
|
|
71
|
+
const started = new Date(startedAt);
|
|
72
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
73
|
+
const time = `${pad(started.getHours())}:${pad(started.getMinutes())}`;
|
|
74
|
+
if (started.toDateString() === (/* @__PURE__ */ new Date()).toDateString()) return time;
|
|
75
|
+
return `${started.getFullYear()}-${pad(started.getMonth() + 1)}-${pad(started.getDate())} ${time}`;
|
|
76
|
+
}
|
|
77
|
+
function refusal(holder) {
|
|
78
|
+
if (!holder)
|
|
79
|
+
return new Error(
|
|
80
|
+
`The workspace lock ${LOCK_FILE} cannot be read, so another farseer code command may be running in this workspace. ${deleteAdvice}`
|
|
81
|
+
);
|
|
82
|
+
const host = holder.hostname === os.hostname() ? "" : ` on ${holder.hostname}`;
|
|
83
|
+
return new Error(
|
|
84
|
+
`Another farseer code command is running in this workspace: ${holder.command}, pid ${holder.pid}${host}, started ${startedLabel(holder.startedAt)}. ${deleteAdvice}`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
function create(file, content) {
|
|
88
|
+
let descriptor;
|
|
89
|
+
try {
|
|
90
|
+
descriptor = fs.openSync(file, "wx");
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.code === "EEXIST") return false;
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
fs.writeSync(descriptor, content);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
fs.closeSync(descriptor);
|
|
99
|
+
fs.rmSync(file, { force: true });
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
fs.closeSync(descriptor);
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
function acquireWorkspaceLock(root, command) {
|
|
106
|
+
const file = lockPath(root);
|
|
107
|
+
const content = JSON.stringify({
|
|
108
|
+
pid: process.pid,
|
|
109
|
+
hostname: os.hostname(),
|
|
110
|
+
command,
|
|
111
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
112
|
+
});
|
|
113
|
+
if (!create(file, content)) {
|
|
114
|
+
const found = readLock(file);
|
|
115
|
+
const stale = found?.holder && found.holder.hostname === os.hostname() && !running(found.holder.pid);
|
|
116
|
+
if (found && !stale) throw refusal(found.holder);
|
|
117
|
+
if (found && readLock(file)?.text === found.text) fs.rmSync(file, { force: true });
|
|
118
|
+
if (!create(file, content)) throw refusal(readLock(file)?.holder);
|
|
119
|
+
}
|
|
120
|
+
let held = true;
|
|
121
|
+
const release = () => {
|
|
122
|
+
if (!held) return;
|
|
123
|
+
held = false;
|
|
124
|
+
process.removeListener("exit", release);
|
|
125
|
+
try {
|
|
126
|
+
if (fs.readFileSync(file, "utf8") === content) fs.unlinkSync(file);
|
|
127
|
+
} catch {
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
process.on("exit", release);
|
|
131
|
+
if (!process.listeners("SIGINT").includes(import_layoutReceipt.exitAfterWrites)) process.on("SIGINT", import_layoutReceipt.exitAfterWrites);
|
|
132
|
+
return release;
|
|
133
|
+
}
|
|
134
|
+
async function withWorkspaceLock(root, command, action) {
|
|
135
|
+
const release = acquireWorkspaceLock(root, command);
|
|
136
|
+
try {
|
|
137
|
+
return await action();
|
|
138
|
+
} finally {
|
|
139
|
+
release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
143
|
+
0 && (module.exports = {
|
|
144
|
+
LOCK_FILE,
|
|
145
|
+
acquireWorkspaceLock,
|
|
146
|
+
withWorkspaceLock
|
|
147
|
+
});
|
|
148
|
+
//# sourceMappingURL=workspaceLock.js.map
|