@slim-lang/spm 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import { readJson, rootPath } from "../helpers.js"
4
+
5
+ export function lockFile(dir = rootPath) {
6
+ return path.join(dir, "spm.lock.json")
7
+ }
8
+
9
+ export function readLock(dir = rootPath) {
10
+ try {
11
+ const data = readJson(lockFile(dir))
12
+ if (!data.packages || typeof data.packages !== "object") data.packages = {}
13
+ return data
14
+ } catch {
15
+ return { packages: {} }
16
+ }
17
+ }
18
+
19
+ export function writeLock(data, dir = rootPath) {
20
+ fs.writeFileSync(lockFile(dir), JSON.stringify(data, null, 4) + "\n", "utf8")
21
+ return data
22
+ }
23
+
24
+ export function setLockEntry(name, entry, dir = rootPath) {
25
+ const lock = readLock(dir)
26
+ lock.packages[name] = entry
27
+ return writeLock(lock, dir)
28
+ }
29
+
30
+ export function removeLockEntry(name, dir = rootPath) {
31
+ const lock = readLock(dir)
32
+ if (name in lock.packages) {
33
+ delete lock.packages[name]
34
+ writeLock(lock, dir)
35
+ }
36
+ return lock
37
+ }
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs/promises"
2
+ import path from "node:path"
3
+
4
+ export const DEFAULT_IGNORES = ["node_modules/", "slim-dist/", "spm.lock.json", ".DS_Store", "Thumbs.db"]
5
+
6
+ function escapeRegex(char) {
7
+ return /[.*+?^${}()|[\]\\/]/.test(char) ? `\\${char}` : char
8
+ }
9
+
10
+ function globToRegex(glob, anchored) {
11
+ let source = ""
12
+
13
+ for (let i = 0; i < glob.length; i++) {
14
+ const char = glob[i]
15
+
16
+ if (char === "*") {
17
+ if (glob[i + 1] === "*" && (i === 0 || glob[i - 1] === "/")) {
18
+ if (i + 2 === glob.length) {
19
+ source += ".*"
20
+ i += 1
21
+ continue
22
+ }
23
+ if (glob[i + 2] === "/") {
24
+ source += "(?:.*/)?"
25
+ i += 2
26
+ continue
27
+ }
28
+ }
29
+ source += "[^/]*"
30
+ }
31
+ else if (char === "?") {
32
+ source += "[^/]"
33
+ }
34
+ else if (char === "[") {
35
+ const end = glob.indexOf("]", i + 2)
36
+ if (end === -1) {
37
+ source += "\\["
38
+ continue
39
+ }
40
+ let set = glob.slice(i + 1, end).replaceAll("\\", "\\\\")
41
+ if (set[0] === "!") set = "^" + set.slice(1)
42
+ source += `[${set}]`
43
+ i = end
44
+ }
45
+ else if (char === "\\" && i + 1 < glob.length) {
46
+ source += escapeRegex(glob[++i])
47
+ }
48
+ else {
49
+ source += escapeRegex(char)
50
+ }
51
+ }
52
+
53
+ return new RegExp(`^${anchored ? "" : "(?:.*/)?"}${source}$`)
54
+ }
55
+
56
+ export function parseIgnore(content, base = "") {
57
+ const rules = []
58
+
59
+ for (const raw of content.split(/\r?\n/)) {
60
+ let line = raw.replace(/(?<!\\)\s+$/, "")
61
+ if (!line || line.startsWith("#")) continue
62
+
63
+ let negate = false
64
+ if (line.startsWith("!")) {
65
+ negate = true
66
+ line = line.slice(1)
67
+ }
68
+ else if (line.startsWith("\\!") || line.startsWith("\\#")) {
69
+ line = line.slice(1)
70
+ }
71
+
72
+ let dirOnly = false
73
+ if (line.endsWith("/")) {
74
+ dirOnly = true
75
+ line = line.replace(/\/+$/, "")
76
+ }
77
+ if (!line) continue
78
+
79
+ const anchored = line.includes("/")
80
+ line = line.replace(/^\/+/, "")
81
+ if (!line) continue
82
+
83
+ rules.push({ base, negate, dirOnly, regex: globToRegex(line, anchored) })
84
+ }
85
+
86
+ return rules
87
+ }
88
+
89
+ export function isIgnored(rules, relPath, isDir) {
90
+ let ignored = false
91
+
92
+ for (const rule of rules) {
93
+ if (rule.dirOnly && !isDir) continue
94
+ if (rule.base && !relPath.startsWith(rule.base)) continue
95
+ if (rule.regex.test(relPath.slice(rule.base.length))) ignored = !rule.negate
96
+ }
97
+
98
+ return ignored
99
+ }
100
+
101
+ async function readIgnoreFile(file, base) {
102
+ try {
103
+ return parseIgnore(await fs.readFile(file, "utf8"), base)
104
+ }
105
+ catch (error) {
106
+ if (error.code === "ENOENT" || error.code === "EISDIR") return []
107
+ throw error
108
+ }
109
+ }
110
+
111
+ export async function getPackageFiles(dir) {
112
+ const files = []
113
+
114
+ async function walk(absDir, relDir, inherited) {
115
+ const own = await readIgnoreFile(path.join(absDir, ".gitignore"), relDir ? `${relDir}/` : "")
116
+ const rules = own.length ? [...inherited, ...own] : inherited
117
+ const entries = await fs.readdir(absDir, { withFileTypes: true })
118
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
119
+
120
+ for (const entry of entries) {
121
+ if (entry.name === ".git") continue
122
+
123
+ const relPath = relDir ? `${relDir}/${entry.name}` : entry.name
124
+ const isDir = entry.isDirectory()
125
+ if (isIgnored(rules, relPath, isDir)) continue
126
+
127
+ if (isDir) await walk(path.join(absDir, entry.name), relPath, rules)
128
+ else if (entry.isFile()) files.push({ path: relPath, fullPath: path.join(absDir, entry.name) })
129
+ }
130
+ }
131
+
132
+ await walk(dir, "", parseIgnore(DEFAULT_IGNORES.join("\n")))
133
+ return files
134
+ }
@@ -0,0 +1,120 @@
1
+ import { commitPackage, createGitHubTag, getBranchHead, githubRequest, tagExists } from "./github_req.js"
2
+ import { getPackage, publishPackage, updatePackage } from "./spm.js"
3
+ import { getPackageFiles } from "./package_files.js"
4
+
5
+ export const APP_INSTALL_URL = "https://github.com/apps/slim-package-manager/installations/new"
6
+
7
+ const VERSION = /^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?$/
8
+
9
+ export function parseVersion(value) {
10
+ const match = VERSION.exec(String(value ?? ""))
11
+ if (!match) return null
12
+ return { parts: match[1].split(".").map(Number), pre: match[2] ? match[2].split(".") : [] }
13
+ }
14
+
15
+ export function compareVersions(a, b) {
16
+ const left = parseVersion(a)
17
+ const right = parseVersion(b)
18
+ if (!left || !right) throw new Error(`Cannot compare versions "${a}" and "${b}"`)
19
+
20
+ for (let i = 0; i < Math.max(left.parts.length, right.parts.length); i++) {
21
+ const diff = (left.parts[i] ?? 0) - (right.parts[i] ?? 0)
22
+ if (diff !== 0) return Math.sign(diff)
23
+ }
24
+
25
+ if (!left.pre.length || !right.pre.length) return Math.sign(right.pre.length - left.pre.length)
26
+
27
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i++) {
28
+ const x = left.pre[i]
29
+ const y = right.pre[i]
30
+ if (x === undefined) return -1
31
+ if (y === undefined) return 1
32
+ if (x === y) continue
33
+ const xn = /^\d+$/.test(x)
34
+ const yn = /^\d+$/.test(y)
35
+ if (xn && yn) return Math.sign(Number(x) - Number(y))
36
+ if (xn) return -1
37
+ if (yn) return 1
38
+ return x < y ? -1 : 1
39
+ }
40
+
41
+ return 0
42
+ }
43
+
44
+ function fail(msg, extra = {}) {
45
+ return { success: false, msg, ...extra }
46
+ }
47
+
48
+ export async function preparePublish({ token, name, dir, spm }) {
49
+ const repo = spm.github?.repo
50
+ const version = spm.version
51
+ const tag = `v${version}`
52
+
53
+ if (!repo) return fail("The .spm file has no @github repo")
54
+ if (!parseVersion(version)) return fail(`version "${version}" in .spm is not a version like 1.2.0`)
55
+ if (!token) return fail("Not signed in to GitHub: run spm login")
56
+
57
+ const installations = await githubRequest(token, "/user/installations")
58
+ if (!installations?.total_count) {
59
+ return fail(`The slim-package-manager GitHub App is not installed on "${repo}"`, { appMissing: true })
60
+ }
61
+
62
+ const repository = await githubRequest(token, `/repos/${repo}`)
63
+ const branch = repository.default_branch || "main"
64
+
65
+ let parent
66
+ try {
67
+ parent = await getBranchHead(token, repo, branch)
68
+ }
69
+ catch (error) {
70
+ throw new Error(`Cannot read branch ${branch} of ${repo}: ${error.message}`)
71
+ }
72
+
73
+ const registry = await getPackage({ name })
74
+ const existing = registry.success ? registry.content : null
75
+ let registryUpToDate = false
76
+
77
+ if (existing?.latest) {
78
+ const order = compareVersions(version, existing.latest)
79
+ if (order < 0) return fail(`version ${version} is below the registry's latest ${existing.latest}: raise version in .spm`)
80
+ registryUpToDate = order === 0
81
+ }
82
+
83
+ if (await tagExists(token, repo, tag)) {
84
+ return fail(`${repo} already has the tag ${tag}: raise version in .spm`)
85
+ }
86
+
87
+ const files = await getPackageFiles(dir)
88
+ if (files.length === 0) return fail("Package directory is empty")
89
+
90
+ return {
91
+ success: true,
92
+ plan: { name, repo, branch, parent, version, tag, description: spm.description, files, existing: !!existing, registryUpToDate }
93
+ }
94
+ }
95
+
96
+ export async function runPublish({ token, plan }) {
97
+ const { name, repo, branch, parent, version, tag, description, files } = plan
98
+
99
+ const pushed = await commitPackage({ token, repo, branch, parent, files, message: `Release ${version}` })
100
+ const pushedNote = pushed.changed ? `${repo} now has the commit ${pushed.commit.slice(0, 7)}, ` : ""
101
+
102
+ if (!plan.registryUpToDate) {
103
+ const request = plan.existing ? updatePackage : publishPackage
104
+ const registry = await request({ token, name, description, version, github: repo })
105
+ if (!registry.success) {
106
+ return fail(`SPM registry: ${registry.content ?? "request failed"} (${pushedNote}nothing tagged; run spm publish again)`, { pushed })
107
+ }
108
+ }
109
+
110
+ const tagged = await createGitHubTag(token, repo, version, pushed.commit)
111
+ if (!tagged.success) {
112
+ return fail(`@${name} ${version} is in the registry, but tagging ${tag} on GitHub failed: ${tagged.msg} (run spm publish again)`, { pushed })
113
+ }
114
+
115
+ return {
116
+ success: true,
117
+ msg: `@${name} ${version} published: ${repo} ${tag} @ ${pushed.commit.slice(0, 7)}${pushed.changed ? "" : " (files unchanged, no new commit)"}`,
118
+ pushed
119
+ }
120
+ }
package/src/api/spm.js ADDED
@@ -0,0 +1,32 @@
1
+ const API_URL = "https://spm.yurba.one"
2
+
3
+ async function request(endpoint, body) {
4
+ const res = await fetch(`${API_URL}${endpoint}`, body === undefined
5
+ ? { method: "GET", headers: { "Content-Type": "application/json" } }
6
+ : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
7
+
8
+ let data
9
+ try {
10
+ data = await res.json()
11
+ } catch {
12
+ return { success: false, content: `SPM registry returned HTTP ${res.status}` }
13
+ }
14
+
15
+ return { success: !!data.success, content: data.result }
16
+ }
17
+
18
+ export function publishPackage({ token, name, version, github, description = "" }) {
19
+ return request("/publish", { github_token: token, name, description, version, github })
20
+ }
21
+
22
+ export function getPackage({ name }) {
23
+ return request(`/install?name=${encodeURIComponent(name)}`)
24
+ }
25
+
26
+ export function updatePackage({ token, name, description, version, github }) {
27
+ return request("/update", { github_token: token, name, description, version, github })
28
+ }
29
+
30
+ export function removePackage({ token, name }) {
31
+ return request("/remove", { github_token: token, name })
32
+ }
@@ -0,0 +1,30 @@
1
+ import keytar from "keytar";
2
+
3
+ const SERVICE = "slim-package-manager";
4
+ const ACCOUNT = "github";
5
+
6
+ export async function saveGitHubToken(token) {
7
+ if (!token) {
8
+ throw new Error("GitHub token is empty");
9
+ }
10
+
11
+ await keytar.setPassword(
12
+ SERVICE,
13
+ ACCOUNT,
14
+ token
15
+ );
16
+ }
17
+
18
+ export async function getGitHubToken() {
19
+ return await keytar.getPassword(
20
+ SERVICE,
21
+ ACCOUNT
22
+ );
23
+ }
24
+
25
+ export async function deleteGitHubToken() {
26
+ return await keytar.deletePassword(
27
+ SERVICE,
28
+ ACCOUNT
29
+ );
30
+ }