@bluestep-systems/b6p-core-bsjs-git 0.0.0-stage → 0.3.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 CHANGED
@@ -1,3 +1,158 @@
1
- # Temporary Holding Version
1
+ # @bluestep-systems/b6p-core-bsjs-git
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Browser- and Node-safe git client for BlueStep BSJS scripts. It edits a script's **draft** branch with
4
+ [isomorphic-git](https://isomorphic-git.org/) through the platform's git proxy (`<org>/git/<classid>___<seqnum>`),
5
+ asks the platform to build it, publishes it, reads git history, and reads the legacy (pre-git) history archive. No
6
+ WebDAV, no Node built-in imports, no compiler: the file system is injected, HTTP is `fetch`, and the platform compiles.
7
+
8
+ Used by [`@bluestep-systems/b6p-core`](../../README.md) (re-exported as `bsjsGit`) and by the BSJS editor.
9
+
10
+ ```ts
11
+ import { ScriptRepo, LegacyHistoryClient, parseCompoundId } from "@bluestep-systems/b6p-core-bsjs-git";
12
+
13
+ const repo = new ScriptRepo({
14
+ fs, // Node's `fs`, or a browser one such as LightningFS (needs `.promises`)
15
+ dir: "/work/654015___1001",
16
+ script: parseCompoundId("654015___1001"),
17
+ baseUrl: "https://org.bluestep.net/",
18
+ auth: { kind: "token", token }, // a b6pt_ token; or { kind: "session" } in a signed-in browser
19
+ author: { name: "Ada", email: "ada@example.com" }, // always the caller's; there is no default identity
20
+ });
21
+
22
+ await repo.ensureGitMode(); // WEBDAV script -> git (one-way); no-op when already git. Returns the clone URL
23
+ await repo.clone(); // every branch; draft checked out (or clone({ ensureGit: true }) for both)
24
+ // clone({ depth: 50, singleBranch: true }): a bounded clone (plus master's head at the same depth);
25
+ // repo.deepen(50) loads older history; repo.logPage(...).shallowBoundary says when to
26
+ await repo.writeFile("main.ts", "export {};\n");
27
+ await repo.commit("Edit main"); // stages every working-tree change
28
+ // commit(msg, author, { parents }) makes a (merge) commit over the given parents even with nothing staged
29
+ await repo.push(); // the draft branch
30
+ // commit(msg, author, { force: [".build/app.js"] }) stages those paths even when .gitignore matches them
31
+ const build = await repo.compileDraft(); // the platform builds the pushed draft; the local draft moves to its build commit
32
+ // { compile, buildCommitSha, vouched, head, fastForward }
33
+ const { publishedSha, refreshed } = await repo.publish(); // the platform promotes draft (the build commit) to master
34
+
35
+ await repo.sha("origin/draft"); // a branch or sha as a commit sha
36
+ await repo.isAncestor(a, b); // whether a is b or one of its ancestors
37
+ await repo.resetDraft(sha); // move the local draft and its working tree to a commit
38
+
39
+ await repo.log({ rev: "master", limit: 20 }); // CommitInfo[], newest first; page with `before`
40
+ await repo.listTree(publishedSha); // files at a revision
41
+ await repo.readText(publishedSha, "main.ts");
42
+ await repo.diff(a, b); // FileChange[] between two revisions
43
+
44
+ const legacy = new LegacyHistoryClient({ baseUrl, auth: { kind: "token", token } });
45
+ const entries = await legacy.list("654015___1001", { limit: 50 }); // newest first
46
+ const tree = await legacy.get("654015___1001", entries[0].id); // saveState v1 or v0, one tree type
47
+ ```
48
+
49
+ Paths are `/`-separated and stay inside the working tree: a backslash, `..` or a `.git` segment is refused.
50
+
51
+ ## Refusals
52
+
53
+ Every refusal is a typed `BsjsGitError` with a `code`: `GitAuthError` (401), `GitPushNotEnabledError` (the script
54
+ publishes over WebDAV, so its repo is read-only), `GitCodeLockedError`, `GitPermissionError` (other 403),
55
+ `GitRepoNotFoundError` (404: no repo, not visible, or git integration off), `GitPushRejectedError` (the forge refused
56
+ the ref; `protectedBranch` for master), `GitNotFastForwardError`, `PublishRefusedError` (`reason` is the server's
57
+ `PUBLISH_REFUSED` reason), `DraftBuildFailedError` / `DraftBuildMovedError` (the build), `GitBuildFastForwardBlockedError` (`paths`), `GitUnpushedChangesError`,
58
+ `GitIdentityError`, `GitTransportError`.
59
+
60
+ ## Auth modes
61
+
62
+ `auth: { kind: "token", token }` sends the `b6pt_` token (Basic to the git proxy, Bearer to `/gql` and REST). `auth:
63
+ { kind: "session" }` is for a browser already signed in: no `Authorization` header, `credentials: "include"`, and the
64
+ `B6P-CSRF-TOKEN` from `/csrf-token` on every request (git smart-HTTP, `/gql`, legacy history), refreshed tokens adopted
65
+ and a refused one retried once. Session mode relies on the platform's git proxy accepting the session (web item W6).
66
+
67
+ ## Switching a script to git
68
+
69
+ `ensureGitMode()` reads the script's `gitPublishing` / `gitCloneUrl` and, only if it is not in GIT mode, runs
70
+ `enableGitPublishing: true` on the script's update mutation (synchronous, creates and seeds the repo, **one-way**).
71
+ `ensureGitModeResult()` is the same, also saying whether this call did the switch. `clone({ ensureGit: true })` does it first; a plain `clone()` never flips a script.
72
+ The mode is read with a real query, `remoteObject(id: "<classid>___<seqnum>") { ... on ScriptFormula|ScriptMergeReport|ScriptEndpoint { gitPublishing gitCloneUrl } }`, not a write.
73
+
74
+ ## Build
75
+
76
+ Nothing compiles in this package or in the editor: `compileDraft()` asks the platform to build the draft it holds. The
77
+ local draft must already be pushed (`GitUnpushedChangesError` otherwise). It sends the script's update mutation with
78
+ `compileDraft: true` and `expectedDraftSha` (the pushed head) on `/gql`; the platform compiles the draft branch at that
79
+ commit against its siblings' snapshots and commits the output and stale-output deletes, plus the build manifest only when
80
+ it vouches for the build (every project's output written, no blocking error; a type-checker finding is a warning), as one
81
+ build commit authored by the caller. The answer's `extensions.bluestepCompile[0]` is the compile (`status`, counts,
82
+ `diagnostics`, `gate`; `parseDraftCompileOutcome`) and `extensions.bluestepBuild[0]` the build commit (`{ commit,
83
+ vouched }` of `{ script, draftSha, commit, built, vouched, status }`; `parseDraftBuildCommit`; `vouched` is also true
84
+ for a draft that needs no manifest). The local draft is then moved exactly to the build commit by
85
+ `fastForwardToBuild(sha)`: the working tree and index first, for exactly the paths the build changed (straight into the
86
+ index, whatever `.gitignore` says), the branch last. A path whose local copy matches neither the pushed commit nor the
87
+ build (a local edit, an untracked or ignored file) stops it before anything is touched; other local edits are kept. The
88
+ outcome is `fastForward: { state, blockedPaths, error }` (`fast-forwarded`, `unchanged`, `blocked`, `failed`), never a
89
+ build failure. `isBuildCommitOf(candidate, base)` says whether a commit is the platform's build of exactly the source `base`, or a
90
+ rebuild chain of it: each commit carries the trailer `Bluestep-Build-Of: <base>` (`buildSourceOf`, `BUILD_OF_TRAILER`),
91
+ has one parent and changes only paths under the output folder of some build project at the parent: each
92
+ `tsconfig.json` at any depth gives `<its dir>/` + its `buildOutputFolder`, plus the root `jsconfig.json` when there is
93
+ no root `tsconfig.json`; a project whose folder is empty or leaves the tree gives none, and with none at all nothing is
94
+ a build (`buildConfigPaths`, `buildOutputFolders`, `changesOnlyBuildOutput`: the one resolver web and the BSJS editor
95
+ use too). A chain is at most 16 build commits deep. The subject never counts. This is
96
+ web's rule (`docs/bsjs-git-snapshot-design.md`, "Build commits"), the trailer parsed as there: CRLF as LF, trailing
97
+ whitespace dropped, the last paragraph (after the last blank or whitespace-only line, or the whole message), exactly one
98
+ line `Bluestep-Build-Of: <40/64 hex>`. Rule 3 compares complete tree entries (mode and id, gitlinks included), so a
99
+ mode-only or submodule change outside `F/` is not a build.
100
+
101
+ A refusal with reason `BUILD_OUTCOME_UNKNOWN` (the platform could not confirm its build push) is never retried, since a repeat could build twice: `compileDraft` reads the draft back and returns
102
+ `outcomeUnknown: { buildFound }`, moving the local draft to the head when that is a build of the push. `compile` is
103
+ then `UNKNOWN` and `vouched` false. It is for taking
104
+ in a build whose answer was lost. An unclean build deletes the manifest, and the fast-forward deletes it here too.
105
+
106
+ It resolves to `{ compile, buildCommitSha, vouched, head, fastForward }`: `buildCommitSha` is `null` when the build made no commit
107
+ (already built at that commit, nothing to build). An unclean build (`vouched: false`) still commits its output, without
108
+ a manifest, so `publish()` is refused until a clean build. `BUSY` is retried 3 times 5 s apart, `INPUT_INCOMPLETE` 3
109
+ times 2 s apart, `COMPILER_UNAVAILABLE` and a failed request once (`COMPILE_RETRY`; `options.sleep` replaces the
110
+ timer). A tripped gate or withheld emit is a result (`compile.status`; `compileAllowsPublish` says whether to publish).
111
+ A draft that moved since the push is `DraftBuildMovedError` (`DRAFT_MOVED`); any other failure is
112
+ `DraftBuildFailedError` (`messages`, `networkFailure`).
113
+
114
+ ## Publish
115
+
116
+ `publish({ at })` pins the publish to the commit that was built and checked (the build commit, or the pushed commit
117
+ when there was none): the local draft must be that commit or a build of it (`isBuildCommitOf`), else
118
+ `PublishPinMismatchError` (`at`, `local`) is thrown with nothing sent, so a later save cannot be published under an
119
+ earlier build's result. b6p-core always pins.
120
+
121
+ Build refusals are `DraftBuildFailedError` with a typed `reason` (`DRAFT_BUILD_REFUSAL_REASONS`: `DRAFT_MOVED`,
122
+ `BUILD_OUTCOME_UNKNOWN`, `DRAFT_TOO_LARGE`, `REPO_MISSING`, `DRAFT_BRANCH_MISSING`; `rawReason` keeps a newer one) and
123
+ are never retried.
124
+
125
+ The mutation carries `expectedDraftSha`: the local draft head `publish()` verified equals the platform's. If the platform's draft moved since (someone pushed in between), it refuses with reason `DRAFT_MOVED`, thrown as `PublishDraftMovedError` (a `PublishRefusedError`), and publishes nothing. `gitMode()` reads the mode without switching anything.
126
+
127
+ `publish()` sends the platform's existing publish: a GraphQL `updateScript<Type>` mutation with `takeSnapshot: true`
128
+ on `/gql`, reading `config.publishedSha` from the answer. The local draft must already be pushed. `/gql` enforces
129
+ the CSRF token on every call, bearer included, so the call mirrors `b6p-core`'s `csrfFetch`: the bearer opens a session,
130
+ the token is read from `/csrf-token` and sent as `B6P-CSRF-TOKEN` with the session cookie (kept in a small jar in Node;
131
+ a browser keeps its own), and a refused token is retried once. It resolves to `{ publishedSha, refreshed, refreshError? }`:
132
+ the publish has happened once it resolves, and `refreshed: false` only means the follow-up fetch of `origin/master` failed.
133
+
134
+ ## Bundling for a browser
135
+
136
+ isomorphic-git needs a global `Buffer`, and its `safe-buffer` dependency requires `"buffer"`. This package depends on the
137
+ npm `buffer` package (pinned) and installs it as `globalThis.Buffer` when none exists (the first thing its entry does),
138
+ so a bundler resolves `"buffer"` to it with no polyfill plugin and no alias. `test/BrowserBundle.test.js` bundles the
139
+ package with esbuild (`platform: "browser"`, no plugins) to keep that true.
140
+
141
+ ## Tests
142
+
143
+ `npm test -w @bluestep-systems/b6p-core-bsjs-git`. The round-trip spec serves a real bare repo over HTTP by running
144
+ `git http-backend` behind `node:http` (see `test/support/GitProxyStub.js`), so `git` must be on the PATH.
145
+
146
+ ## Build manifest
147
+
148
+ A git script publishes `draft` exactly as committed, so the server refuses a draft whose sources no longer match the
149
+ build manifest (`<outDir>/.b6p-build.json`, contract v1): the git blob SHA-1 of every source file the build was made
150
+ from. The platform writes it in its build commit (see Build), only for a clean build; no client writes one, and this
151
+ package has no manifest writer (0.3.0 removed `commit({ buildManifest })`, `planBuildManifest`, `formatBuildManifest`,
152
+ `gitBlobSha1` and `BUILD_MANIFEST_BUILDER`). None is needed for an externally built script, a tree with no
153
+ `tsconfig.json`, or a draft with no TypeScript source outside the output folder (`isTypeScriptSource`: `ts tsx mts
154
+ cts`, never a `*.d.*` declaration). The layout helpers (`buildOutputFolder`, `buildManifestPath`, `isBuildSource`,
155
+ `isTypeScriptSource`, `hasNoTsconfig`, `parseJsonc`) stay exported for reading. A refused publish is
156
+ `PublishBuildStaleError` (`BUILD_STALE`), `PublishBuildManifestMissingError` (`BUILD_MANIFEST_MISSING`) or
157
+ `PublishBuildManifestInvalidError` (`BUILD_MANIFEST_INVALID`), each with `withheld` (the stale paths, or the
158
+ manifest's path).