@namzu/sdk 69.2.0 → 69.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/constants/plugin/index.d.ts +8 -0
  3. package/dist/constants/plugin/index.d.ts.map +1 -1
  4. package/dist/constants/plugin/index.js +8 -0
  5. package/dist/constants/plugin/index.js.map +1 -1
  6. package/dist/plugin/common-layout/index.d.ts +5 -0
  7. package/dist/plugin/common-layout/index.d.ts.map +1 -0
  8. package/dist/plugin/common-layout/index.js +3 -0
  9. package/dist/plugin/common-layout/index.js.map +1 -0
  10. package/dist/plugin/common-layout/mcp.d.ts +21 -0
  11. package/dist/plugin/common-layout/mcp.d.ts.map +1 -0
  12. package/dist/plugin/common-layout/mcp.js +305 -0
  13. package/dist/plugin/common-layout/mcp.js.map +1 -0
  14. package/dist/plugin/common-layout/paths.d.ts +27 -0
  15. package/dist/plugin/common-layout/paths.d.ts.map +1 -0
  16. package/dist/plugin/common-layout/paths.js +48 -0
  17. package/dist/plugin/common-layout/paths.js.map +1 -0
  18. package/dist/plugin/common-layout/read.d.ts +25 -0
  19. package/dist/plugin/common-layout/read.d.ts.map +1 -0
  20. package/dist/plugin/common-layout/read.js +1155 -0
  21. package/dist/plugin/common-layout/read.js.map +1 -0
  22. package/dist/plugin/common-layout/types.d.ts +66 -0
  23. package/dist/plugin/common-layout/types.d.ts.map +1 -0
  24. package/dist/plugin/common-layout/types.js +2 -0
  25. package/dist/plugin/common-layout/types.js.map +1 -0
  26. package/dist/plugin/common-layout-names.d.ts +65 -0
  27. package/dist/plugin/common-layout-names.d.ts.map +1 -0
  28. package/dist/plugin/common-layout-names.js +94 -0
  29. package/dist/plugin/common-layout-names.js.map +1 -0
  30. package/dist/plugin/hook-module/capabilities.d.ts +41 -0
  31. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -0
  32. package/dist/plugin/hook-module/capabilities.js +438 -0
  33. package/dist/plugin/hook-module/capabilities.js.map +1 -0
  34. package/dist/plugin/hook-module/consent.d.ts +39 -0
  35. package/dist/plugin/hook-module/consent.d.ts.map +1 -0
  36. package/dist/plugin/hook-module/consent.js +59 -0
  37. package/dist/plugin/hook-module/consent.js.map +1 -0
  38. package/dist/plugin/hook-module/events.d.ts +33 -0
  39. package/dist/plugin/hook-module/events.d.ts.map +1 -0
  40. package/dist/plugin/hook-module/events.js +149 -0
  41. package/dist/plugin/hook-module/events.js.map +1 -0
  42. package/dist/plugin/hook-module/host.d.ts +79 -0
  43. package/dist/plugin/hook-module/host.d.ts.map +1 -0
  44. package/dist/plugin/hook-module/host.js +546 -0
  45. package/dist/plugin/hook-module/host.js.map +1 -0
  46. package/dist/plugin/hook-module/index.d.ts +11 -0
  47. package/dist/plugin/hook-module/index.d.ts.map +1 -0
  48. package/dist/plugin/hook-module/index.js +6 -0
  49. package/dist/plugin/hook-module/index.js.map +1 -0
  50. package/dist/plugin/hook-module/scan.d.ts +99 -0
  51. package/dist/plugin/hook-module/scan.d.ts.map +1 -0
  52. package/dist/plugin/hook-module/scan.js +789 -0
  53. package/dist/plugin/hook-module/scan.js.map +1 -0
  54. package/dist/plugin/hook-module/worker-source.d.ts +31 -0
  55. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -0
  56. package/dist/plugin/hook-module/worker-source.js +498 -0
  57. package/dist/plugin/hook-module/worker-source.js.map +1 -0
  58. package/dist/plugin/index.d.ts +5 -2
  59. package/dist/plugin/index.d.ts.map +1 -1
  60. package/dist/plugin/index.js +4 -1
  61. package/dist/plugin/index.js.map +1 -1
  62. package/dist/plugin/lifecycle.d.ts +57 -0
  63. package/dist/plugin/lifecycle.d.ts.map +1 -1
  64. package/dist/plugin/lifecycle.js +92 -11
  65. package/dist/plugin/lifecycle.js.map +1 -1
  66. package/dist/plugin/loader.d.ts +30 -0
  67. package/dist/plugin/loader.d.ts.map +1 -1
  68. package/dist/plugin/loader.js +76 -19
  69. package/dist/plugin/loader.js.map +1 -1
  70. package/dist/plugin/shell-hook-env.d.ts +7 -0
  71. package/dist/plugin/shell-hook-env.d.ts.map +1 -1
  72. package/dist/plugin/shell-hook-env.js.map +1 -1
  73. package/dist/plugin/shell-hook.d.ts +10 -1
  74. package/dist/plugin/shell-hook.d.ts.map +1 -1
  75. package/dist/plugin/shell-hook.js +81 -70
  76. package/dist/plugin/shell-hook.js.map +1 -1
  77. package/dist/public-runtime.d.ts +3 -2
  78. package/dist/public-runtime.d.ts.map +1 -1
  79. package/dist/public-runtime.js +2 -2
  80. package/dist/public-runtime.js.map +1 -1
  81. package/dist/skills/loader.d.ts +8 -2
  82. package/dist/skills/loader.d.ts.map +1 -1
  83. package/dist/skills/loader.js +22 -11
  84. package/dist/skills/loader.js.map +1 -1
  85. package/dist/skills/registry.d.ts.map +1 -1
  86. package/dist/skills/registry.js +9 -1
  87. package/dist/skills/registry.js.map +1 -1
  88. package/dist/types/plugin/index.d.ts +73 -0
  89. package/dist/types/plugin/index.d.ts.map +1 -1
  90. package/dist/types/plugin/index.js +28 -6
  91. package/dist/types/plugin/index.js.map +1 -1
  92. package/dist/types/skills/index.d.ts +6 -0
  93. package/dist/types/skills/index.d.ts.map +1 -1
  94. package/package.json +2 -1
  95. package/src/constants/plugin/index.ts +9 -0
  96. package/src/plugin/common-layout/index.ts +19 -0
  97. package/src/plugin/common-layout/mcp.ts +362 -0
  98. package/src/plugin/common-layout/paths.ts +70 -0
  99. package/src/plugin/common-layout/read.ts +1282 -0
  100. package/src/plugin/common-layout/types.ts +77 -0
  101. package/src/plugin/common-layout-names.ts +108 -0
  102. package/src/plugin/hook-module/capabilities.ts +500 -0
  103. package/src/plugin/hook-module/consent.ts +96 -0
  104. package/src/plugin/hook-module/events.ts +177 -0
  105. package/src/plugin/hook-module/host.ts +649 -0
  106. package/src/plugin/hook-module/index.ts +52 -0
  107. package/src/plugin/hook-module/scan.ts +1004 -0
  108. package/src/plugin/hook-module/worker-source.ts +500 -0
  109. package/src/plugin/index.ts +13 -1
  110. package/src/plugin/lifecycle.ts +179 -17
  111. package/src/plugin/loader.ts +97 -18
  112. package/src/plugin/shell-hook-env.ts +7 -0
  113. package/src/plugin/shell-hook.ts +91 -70
  114. package/src/public-runtime.ts +35 -0
  115. package/src/skills/loader.ts +26 -9
  116. package/src/skills/registry.ts +9 -1
  117. package/src/types/plugin/index.ts +81 -24
  118. package/src/types/skills/index.ts +7 -0
@@ -0,0 +1,77 @@
1
+ import type { PluginManifest, PluginRemoteMCPServerConfig } from '../../types/plugin/index.js'
2
+ import type { PluginPathValues } from './paths.js'
3
+
4
+ /**
5
+ * How a finding about a plugin read through the common layout weighs.
6
+ *
7
+ * - `used`: a component Namzu reads and uses.
8
+ * - `ignored`: harmless metadata or a key nothing here reads; shown in details only.
9
+ * - `notUsed`: a feature Namzu has no place for; the plugin still loads.
10
+ * - `refused`: dropped. At entry level (one server, one skill, one hooks file)
11
+ * the plugin loads without it; at plugin level the plugin does not load.
12
+ */
13
+ export type LayoutFindingLevel = 'used' | 'ignored' | 'notUsed' | 'refused'
14
+
15
+ /** A server the reader listed but did not admit because it needs setup, as written in the file. */
16
+ export interface LayoutSetupServer {
17
+ readonly kind: 'remote' | 'local'
18
+ readonly name: string
19
+ /** Remote: the address as written. Local: the command as written. */
20
+ readonly target: string
21
+ readonly args?: readonly string[]
22
+ /** Remote: the transport the entry names. */
23
+ readonly transport?: 'http' | 'sse'
24
+ /** Header or environment values as written, by name. */
25
+ readonly values: Readonly<Record<string, string>>
26
+ }
27
+
28
+ export interface LayoutFinding {
29
+ readonly level: LayoutFindingLevel
30
+ /** A stable kebab-case code, the same for the same cause. */
31
+ readonly code: string
32
+ /** The manifest field or folder the finding is about. */
33
+ readonly field: string
34
+ readonly message: string
35
+ /** The file inside the plugin the finding is about, when it names one. */
36
+ readonly path?: string
37
+ /** On `mcp-needs-setup`: the entry as written, so a consent surface can still show it. */
38
+ readonly server?: LayoutSetupServer
39
+ }
40
+
41
+ /** Where the manifest of a read came from. */
42
+ export type CommonLayoutSource =
43
+ | 'namzu'
44
+ | 'manifest'
45
+ | 'sidecar'
46
+ | 'single-skill'
47
+ | 'conventional'
48
+ | 'none'
49
+
50
+ export interface CommonLayoutOptions {
51
+ /**
52
+ * Read the install sidecar when it is there. Set only by a caller that holds
53
+ * an install record naming this folder: a hand-placed folder and a repository
54
+ * never reach this, so neither can inject components through it.
55
+ */
56
+ readonly entrySidecar?: boolean
57
+ /** Folders the path names stand for besides the plugin's own, by plugin name. */
58
+ readonly paths?: (name: string) => Omit<PluginPathValues, 'root'>
59
+ /** The environment `${VAR}` in a server's `env` is read from. Default `process.env`. */
60
+ readonly environment?: Readonly<Record<string, string | undefined>>
61
+ /** Ids (`name` or `name@marketplace`) already installed, for `dependencies`. Default none. */
62
+ readonly installedIds?: ReadonlySet<string>
63
+ /** A version to use when the manifest names none (the entry's, a commit, a digest). */
64
+ readonly version?: string
65
+ /** A description to use when neither the manifest nor `README.md` gives one. */
66
+ readonly description?: string
67
+ }
68
+
69
+ export interface CommonLayoutRead {
70
+ readonly source: CommonLayoutSource
71
+ /** The manifest to admit; absent when the plugin is refused or is a Namzu `plugin.json`. */
72
+ readonly manifest?: PluginManifest
73
+ readonly remoteServers: readonly PluginRemoteMCPServerConfig[]
74
+ readonly findings: readonly LayoutFinding[]
75
+ /** Set when the whole plugin is refused: the finding that says why. */
76
+ readonly refusal?: LayoutFinding
77
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The literal names of the common plugin layout, in one file.
3
+ *
4
+ * Plugins written for other tools share one on-disk shape, and Namzu reads it
5
+ * so a folder made for that shape runs here unchanged. The file and variable
6
+ * names below belong to that shape, not to Namzu: they are compatibility
7
+ * literals, kept here and nowhere else so the rest of the code, its comments
8
+ * and the docs say "the common plugin layout" and name no one. Every
9
+ * Namzu-facing path and variable keeps its own name (`.namzu`, `NAMZU_*`).
10
+ *
11
+ * This file is allowlisted in `scripts/audit-external-names.mjs` for that
12
+ * reason. Adding a name here is a compatibility decision, not a naming one.
13
+ */
14
+
15
+ /** The folder that holds the common layout's manifest. */
16
+ export const COMMON_MANIFEST_DIR = '.claude-plugin'
17
+
18
+ /** The manifest's file name inside {@link COMMON_MANIFEST_DIR}. */
19
+ export const COMMON_MANIFEST_FILE = 'plugin.json'
20
+
21
+ /** The file of servers at the plugin's root. */
22
+ export const COMMON_MCP_FILE = '.mcp.json'
23
+
24
+ /** The folder of hook entries and the file inside it. */
25
+ export const COMMON_HOOKS_FILE = 'hooks/hooks.json'
26
+
27
+ /** The folders the layout auto-scans, and the root file of a one-skill plugin. */
28
+ export const COMMON_SKILLS_DIR = 'skills'
29
+ export const COMMON_COMMANDS_DIR = 'commands'
30
+ export const COMMON_AGENTS_DIR = 'agents'
31
+ export const COMMON_ROOT_SKILL_FILE = 'SKILL.md'
32
+
33
+ /** Folders that name a component Namzu has no place for. */
34
+ export const COMMON_UNUSED_DIRS: readonly string[] = [
35
+ 'output-styles',
36
+ 'themes',
37
+ 'monitors',
38
+ 'workflows',
39
+ 'bin',
40
+ ]
41
+
42
+ /**
43
+ * The sidecar a marketplace install writes beside the plugin, holding the
44
+ * allow-listed fields of the marketplace entry. Namzu's own name; read only
45
+ * when an install record names the folder.
46
+ */
47
+ export const ENTRY_SIDECAR_FILE = '.namzu-entry.json'
48
+
49
+ /** Variables a plugin's configuration and text may name, as the layout spells them. */
50
+ export const COMMON_ROOT_VARIABLE = 'CLAUDE_PLUGIN_ROOT'
51
+ export const COMMON_DATA_VARIABLE = 'CLAUDE_PLUGIN_DATA'
52
+ export const COMMON_PROJECT_VARIABLE = 'CLAUDE_PROJECT_DIR'
53
+
54
+ /** The same three, spelled for Namzu. */
55
+ export const NAMZU_ROOT_VARIABLE = 'NAMZU_PLUGIN_ROOT'
56
+ export const NAMZU_DATA_VARIABLE = 'NAMZU_PLUGIN_DATA'
57
+ export const NAMZU_PROJECT_VARIABLE = 'NAMZU_PROJECT_DIR'
58
+
59
+ /** The text a plugin's configuration uses for saved options; not supported yet. */
60
+ export const COMMON_USER_CONFIG_PREFIX = 'user_config.'
61
+
62
+ /** A command spelled `/<plugin>:<command>` in the layout's own documentation. */
63
+ export const COMMON_COMMAND_SEPARATOR = ':'
64
+
65
+ /** A marketplace catalog's file name; it sits in {@link COMMON_MANIFEST_DIR} of the marketplace folder. */
66
+ export const COMMON_MARKETPLACE_FILE = 'marketplace.json'
67
+
68
+ /**
69
+ * Marketplace names the layout's own official catalogs use. A marketplace added
70
+ * from anywhere else may not take one, nor a name built from the two words the
71
+ * layout's maker goes by, so a catalog cannot pass itself off as an official one.
72
+ */
73
+ export const COMMON_OFFICIAL_MARKETPLACE_NAMES: readonly string[] = [
74
+ 'claude-code-marketplace',
75
+ 'claude-code-plugins',
76
+ 'claude-plugins-official',
77
+ 'anthropic-marketplace',
78
+ 'anthropic-plugins',
79
+ 'agent-skills',
80
+ 'anthropic-agent-skills',
81
+ 'life-sciences',
82
+ 'knowledge-work-plugins',
83
+ 'claude-for-legal',
84
+ 'claude-for-financial-services',
85
+ 'financial-services-plugins',
86
+ 'first-party-plugins',
87
+ 'claude-tag-plugins',
88
+ 'claude-community',
89
+ 'claude-plugins-community',
90
+ 'healthcare',
91
+ ]
92
+
93
+ /** Whether a marketplace name is an official one of the layout, or built to look like one. */
94
+ export function isOfficialLookingMarketplaceName(name: string): boolean {
95
+ const lower = name.toLowerCase()
96
+ if (COMMON_OFFICIAL_MARKETPLACE_NAMES.includes(lower)) return true
97
+ return /(^|[-_.])(claude|anthropic)([-_.]|$)/.test(lower)
98
+ }
99
+
100
+ /**
101
+ * What a hooks module may import besides its own files: the package that holds
102
+ * its types. A type import is erased before the module runs; a value import of
103
+ * it is refused.
104
+ */
105
+ export const COMMON_MODULE_TYPES_SPECIFIER = 'claude-code'
106
+
107
+ /** The namespace the layout gives its settings-style hook events: `classic.<Event>`. */
108
+ export const COMMON_MODULE_EVENT_NAMESPACE = 'classic'
@@ -0,0 +1,500 @@
1
+ import { type ChildProcess, spawn } from 'node:child_process'
2
+ import {
3
+ closeSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ openSync,
7
+ readFileSync,
8
+ readSync,
9
+ readdirSync,
10
+ realpathSync,
11
+ renameSync,
12
+ statSync,
13
+ writeFileSync,
14
+ } from 'node:fs'
15
+ import { isAbsolute, join, relative, resolve } from 'node:path'
16
+
17
+ import type { Logger } from '../../utils/logger.js'
18
+
19
+ /** The most one read, one output stream or one answer body may hold. */
20
+ export const MAX_CAPABILITY_BYTES = 4 * 1024 * 1024
21
+ /** The most the module's store may hold, as JSON. */
22
+ export const MAX_STORE_BYTES = 1024 * 1024
23
+ export const DEFAULT_PROCESS_TIMEOUT_MS = 30_000
24
+ export const MAX_PROCESS_TIMEOUT_MS = 10 * 60_000
25
+ export const HTTP_TIMEOUT_MS = 30_000
26
+ /** The file the module's store is kept in, inside the plugin's data folder. */
27
+ export const STORE_FILE = 'hook-module-store.json'
28
+
29
+ export interface CapabilityBridgeOptions {
30
+ /** The plugin's own folder. */
31
+ readonly root: string
32
+ /** The folder kept for the plugin's data; without it `$.store` throws. */
33
+ readonly dataDir?: string
34
+ /** The project folder. A relative path and a child's folder are read from it. */
35
+ readonly projectDir: string
36
+ /** The variables the scan found named by literal; `$.env.get` answers no other. */
37
+ readonly envNames: readonly string[]
38
+ /** The environment those variables are read from, and a child inherits. Default `process.env`. */
39
+ readonly environment?: Readonly<Record<string, string | undefined>>
40
+ readonly log: Logger
41
+ readonly pluginName: string
42
+ /** The web fetch. Default the global one. */
43
+ readonly fetch?: typeof fetch
44
+ }
45
+
46
+ export interface CapabilityBridge {
47
+ /** Answer one call on `$`. A throw is the call's rejection. */
48
+ call(noun: string, method: string, args: readonly unknown[]): Promise<unknown>
49
+ /** End every program a module started that is still running. */
50
+ endProcesses(): void
51
+ }
52
+
53
+ /** What a program a module starts inherits of the host's environment, besides names the module reads. */
54
+ const CHILD_ENVIRONMENT = [
55
+ 'PATH',
56
+ 'HOME',
57
+ 'USER',
58
+ 'LOGNAME',
59
+ 'SHELL',
60
+ 'LANG',
61
+ 'LANGUAGE',
62
+ 'TZ',
63
+ 'TERM',
64
+ 'TMPDIR',
65
+ 'TEMP',
66
+ 'TMP',
67
+ 'SystemRoot',
68
+ 'SYSTEMROOT',
69
+ 'USERPROFILE',
70
+ 'APPDATA',
71
+ 'LOCALAPPDATA',
72
+ 'PATHEXT',
73
+ 'COMSPEC',
74
+ ]
75
+
76
+ function isRecord(value: unknown): value is Record<string, unknown> {
77
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
78
+ }
79
+
80
+ function within(root: string, path: string): boolean {
81
+ const rel = relative(root, path)
82
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
83
+ }
84
+
85
+ function realOrSelf(path: string): string {
86
+ try {
87
+ return realpathSync(path)
88
+ } catch {
89
+ return resolve(path)
90
+ }
91
+ }
92
+
93
+ function errorText(error: unknown): string {
94
+ return error instanceof Error ? error.message : String(error)
95
+ }
96
+
97
+ /**
98
+ * What a module may do beyond computing, answered by the host. Every call is
99
+ * checked here and not in the worker: a path is resolved through links before
100
+ * it is compared with the two folders a module may read, a command is an
101
+ * argument list and never a shell line, and a variable is answered only when
102
+ * the scan saw its name written out.
103
+ */
104
+ export function createCapabilityBridge(options: CapabilityBridgeOptions): CapabilityBridge {
105
+ const roots = [realOrSelf(options.root), realOrSelf(options.projectDir)]
106
+ const project = resolve(options.projectDir)
107
+ const environment = options.environment ?? process.env
108
+ const fetchImpl = options.fetch ?? fetch
109
+ const children = new Set<ChildProcess>()
110
+
111
+ /** The path a read may open: lexically and really inside the plugin or the project. */
112
+ const readable = (path: unknown, missingOk = false): { path: string; exists: boolean } => {
113
+ if (typeof path !== 'string' || path === '' || path.includes('\0')) {
114
+ throw new Error('a path is a non-empty string')
115
+ }
116
+ const absolute = isAbsolute(path) ? resolve(path) : resolve(project, path)
117
+ const lexical = [resolve(options.root), project]
118
+ if (
119
+ !lexical.some((root) => within(root, absolute)) &&
120
+ !roots.some((root) => within(root, absolute))
121
+ ) {
122
+ throw new Error(`${path} is outside the plugin and the project folders`)
123
+ }
124
+ let real: string
125
+ try {
126
+ real = realpathSync(absolute)
127
+ } catch (error) {
128
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && missingOk) {
129
+ return { path: absolute, exists: false }
130
+ }
131
+ throw new Error(`${path}: ${errorText(error)}`)
132
+ }
133
+ if (!roots.some((root) => within(root, real))) {
134
+ throw new Error(`${path} leads outside the plugin and the project folders through a link`)
135
+ }
136
+ return { path: real, exists: true }
137
+ }
138
+
139
+ const kindOf = (stats: { isFile(): boolean; isDirectory(): boolean }):
140
+ | 'file'
141
+ | 'dir'
142
+ | 'other' => (stats.isFile() ? 'file' : stats.isDirectory() ? 'dir' : 'other')
143
+
144
+ const fs = {
145
+ read(args: readonly unknown[]): unknown {
146
+ const [path, init] = args
147
+ const { path: real } = readable(path)
148
+ const spec = isRecord(init) ? init : {}
149
+ const as = spec.as === undefined ? 'text' : spec.as
150
+ if (as !== 'text' && as !== 'bytes') throw new Error('as is "text" or "bytes"')
151
+ const offset = spec.offset === undefined ? 0 : spec.offset
152
+ if (typeof offset !== 'number' || !Number.isInteger(offset) || offset < 0) {
153
+ throw new Error('offset is a whole number of bytes')
154
+ }
155
+ const stats = statSync(real)
156
+ if (!stats.isFile()) throw new Error(`${String(path)} is not a regular file`)
157
+ const available = Math.max(0, stats.size - offset)
158
+ const wanted = spec.length === undefined ? available : spec.length
159
+ if (typeof wanted !== 'number' || !Number.isInteger(wanted) || wanted < 0) {
160
+ throw new Error('length is a whole number of bytes')
161
+ }
162
+ if (
163
+ wanted > MAX_CAPABILITY_BYTES ||
164
+ (spec.length === undefined && available > MAX_CAPABILITY_BYTES)
165
+ ) {
166
+ throw new Error(
167
+ `the read is over ${MAX_CAPABILITY_BYTES / 1024 / 1024} MiB; read it in ranges`,
168
+ )
169
+ }
170
+ const count = Math.min(wanted, available)
171
+ const buffer = Buffer.alloc(count)
172
+ if (count > 0) {
173
+ const handle = openSync(real, 'r')
174
+ try {
175
+ readSync(handle, buffer, 0, count, offset)
176
+ } finally {
177
+ closeSync(handle)
178
+ }
179
+ }
180
+ return as === 'bytes' ? { base64: buffer.toString('base64') } : buffer.toString('utf8')
181
+ },
182
+ exists(args: readonly unknown[]): boolean {
183
+ return readable(args[0], true).exists
184
+ },
185
+ stat(args: readonly unknown[]): unknown {
186
+ const { path: real } = readable(args[0])
187
+ const stats = statSync(real)
188
+ const link = lstatSync(
189
+ resolve(isAbsolute(String(args[0])) ? String(args[0]) : join(project, String(args[0]))),
190
+ ).isSymbolicLink()
191
+ const wantsReal = isRecord(args[1]) && args[1].resolve === true
192
+ return {
193
+ kind: kindOf(stats),
194
+ size: stats.isFile() ? stats.size : 0,
195
+ mtimeMs: stats.mtimeMs,
196
+ isLink: link,
197
+ ...(wantsReal ? { realPath: real } : {}),
198
+ }
199
+ },
200
+ list(args: readonly unknown[]): unknown {
201
+ const { path: real } = readable(args[0] === undefined ? '.' : args[0])
202
+ return readdirSync(real, { withFileTypes: true }).map((entry) => {
203
+ const full = join(real, entry.name)
204
+ let size = 0
205
+ let mtimeMs = 0
206
+ try {
207
+ const stats = lstatSync(full)
208
+ if (stats.isFile()) {
209
+ size = stats.size
210
+ mtimeMs = stats.mtimeMs
211
+ }
212
+ } catch {
213
+ // An entry that vanished is listed with no size.
214
+ }
215
+ return {
216
+ name: entry.name,
217
+ kind: entry.isSymbolicLink()
218
+ ? 'other'
219
+ : entry.isFile()
220
+ ? 'file'
221
+ : entry.isDirectory()
222
+ ? 'dir'
223
+ : 'other',
224
+ size,
225
+ mtimeMs,
226
+ isLink: entry.isSymbolicLink(),
227
+ }
228
+ })
229
+ },
230
+ }
231
+
232
+ const storePath = (): string => {
233
+ if (options.dataDir === undefined) {
234
+ throw new Error('this plugin has no data folder, so $.store has nowhere to keep anything')
235
+ }
236
+ return join(options.dataDir, STORE_FILE)
237
+ }
238
+ const readStore = (): Record<string, unknown> => {
239
+ const path = storePath()
240
+ let text: string
241
+ try {
242
+ text = readFileSync(path, 'utf8')
243
+ } catch (error) {
244
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}
245
+ throw error
246
+ }
247
+ const parsed: unknown = JSON.parse(text)
248
+ return isRecord(parsed) ? parsed : {}
249
+ }
250
+ const writeStore = (value: Record<string, unknown>): void => {
251
+ const text = JSON.stringify(value)
252
+ if (Buffer.byteLength(text) > MAX_STORE_BYTES) {
253
+ throw new Error(`the store would be over ${MAX_STORE_BYTES / 1024 / 1024} MiB`)
254
+ }
255
+ const path = storePath()
256
+ mkdirSync(options.dataDir as string, { recursive: true, mode: 0o700 })
257
+ const temporary = `${path}.${process.pid}.tmp`
258
+ writeFileSync(temporary, text, { mode: 0o600 })
259
+ renameSync(temporary, path)
260
+ }
261
+ const storeKey = (key: unknown): string => {
262
+ if (typeof key !== 'string' || key === '' || key.length > 256) {
263
+ throw new Error('a store key is a string of 1 to 256 characters')
264
+ }
265
+ return key
266
+ }
267
+ const store = {
268
+ get(args: readonly unknown[]): unknown {
269
+ return readStore()[storeKey(args[0])]
270
+ },
271
+ set(args: readonly unknown[]): void {
272
+ const key = storeKey(args[0])
273
+ if (args[1] === undefined) throw new Error('a stored value is JSON, not undefined')
274
+ const all = readStore()
275
+ all[key] = args[1]
276
+ writeStore(all)
277
+ },
278
+ delete(args: readonly unknown[]): void {
279
+ const key = storeKey(args[0])
280
+ const all = readStore()
281
+ delete all[key]
282
+ writeStore(all)
283
+ },
284
+ keys(): string[] {
285
+ return Object.keys(readStore())
286
+ },
287
+ }
288
+
289
+ const run = (args: readonly unknown[]): Promise<unknown> => {
290
+ const [argv, init] = args
291
+ if (
292
+ !Array.isArray(argv) ||
293
+ argv.length === 0 ||
294
+ argv.some((part) => typeof part !== 'string' || part.includes('\0')) ||
295
+ argv[0] === ''
296
+ ) {
297
+ return Promise.reject(
298
+ new Error('$.process.run takes an argument list: ["program", "arg", ...]'),
299
+ )
300
+ }
301
+ const spec = isRecord(init) ? init : {}
302
+ let cwd = project
303
+ if (spec.cwd !== undefined) {
304
+ if (typeof spec.cwd !== 'string') return Promise.reject(new Error('cwd is a path'))
305
+ try {
306
+ cwd = readable(spec.cwd).path
307
+ } catch (error) {
308
+ return Promise.reject(error)
309
+ }
310
+ }
311
+ const timeoutMs = spec.timeoutMs === undefined ? DEFAULT_PROCESS_TIMEOUT_MS : spec.timeoutMs
312
+ if (typeof timeoutMs !== 'number' || !(timeoutMs > 0)) {
313
+ return Promise.reject(new Error('timeoutMs is a number of milliseconds'))
314
+ }
315
+ // Not the whole environment: a program a module starts gets the basics and the variables the
316
+ // module reads by name, so a key kept in the environment does not travel to whatever it runs.
317
+ const env: Record<string, string> = {}
318
+ for (const [key, value] of Object.entries(environment)) {
319
+ if (value === undefined) continue
320
+ if (
321
+ CHILD_ENVIRONMENT.includes(key) ||
322
+ key.startsWith('LC_') ||
323
+ options.envNames.includes(key)
324
+ ) {
325
+ env[key] = value
326
+ }
327
+ }
328
+ if (isRecord(spec.env)) {
329
+ for (const [key, value] of Object.entries(spec.env)) {
330
+ if (typeof value === 'string') env[key] = value
331
+ }
332
+ }
333
+ if (spec.stdin !== undefined && typeof spec.stdin !== 'string') {
334
+ return Promise.reject(new Error('stdin is text'))
335
+ }
336
+ const stdin = typeof spec.stdin === 'string' ? spec.stdin : undefined
337
+ return new Promise((resolvePromise, reject) => {
338
+ const child = spawn(argv[0] as string, (argv as string[]).slice(1), {
339
+ cwd,
340
+ env,
341
+ shell: false,
342
+ windowsHide: true,
343
+ stdio: ['pipe', 'pipe', 'pipe'],
344
+ })
345
+ children.add(child)
346
+ child.on('close', () => children.delete(child))
347
+ child.on('error', () => children.delete(child))
348
+ const out: Buffer[] = []
349
+ const err: Buffer[] = []
350
+ let outSize = 0
351
+ let errSize = 0
352
+ let outCut = false
353
+ let errCut = false
354
+ const take = (
355
+ chunk: Buffer,
356
+ into: Buffer[],
357
+ size: number,
358
+ ): { size: number; cut: boolean } => {
359
+ if (size >= MAX_CAPABILITY_BYTES) return { size, cut: true }
360
+ const room = MAX_CAPABILITY_BYTES - size
361
+ const piece = chunk.length > room ? chunk.subarray(0, room) : chunk
362
+ into.push(piece)
363
+ return { size: size + piece.length, cut: chunk.length > room }
364
+ }
365
+ child.stdout.on('data', (chunk: Buffer) => {
366
+ const next = take(chunk, out, outSize)
367
+ outSize = next.size
368
+ outCut ||= next.cut
369
+ })
370
+ child.stderr.on('data', (chunk: Buffer) => {
371
+ const next = take(chunk, err, errSize)
372
+ errSize = next.size
373
+ errCut ||= next.cut
374
+ })
375
+ const timer = setTimeout(
376
+ () => {
377
+ child.kill('SIGKILL')
378
+ reject(
379
+ new Error(
380
+ `${String(argv[0])} did not finish within ${Math.round(Math.min(timeoutMs, MAX_PROCESS_TIMEOUT_MS) / 1000)} seconds and was ended`,
381
+ ),
382
+ )
383
+ },
384
+ Math.min(timeoutMs, MAX_PROCESS_TIMEOUT_MS),
385
+ )
386
+ timer.unref?.()
387
+ child.on('error', (error) => {
388
+ clearTimeout(timer)
389
+ reject(new Error(`${String(argv[0])}: ${error.message}`))
390
+ })
391
+ child.on('close', (code) => {
392
+ clearTimeout(timer)
393
+ resolvePromise({
394
+ exitCode: code ?? 1,
395
+ stdout: Buffer.concat(out).toString('utf8'),
396
+ stderr: Buffer.concat(err).toString('utf8'),
397
+ isStdoutTruncated: outCut,
398
+ isStderrTruncated: errCut,
399
+ })
400
+ })
401
+ child.stdin.on('error', () => undefined)
402
+ child.stdin.end(stdin)
403
+ })
404
+ }
405
+
406
+ const httpFetch = async (args: readonly unknown[]): Promise<unknown> => {
407
+ const [url, init] = args
408
+ if (typeof url !== 'string') throw new Error('$.http.fetch takes a URL')
409
+ let parsed: URL
410
+ try {
411
+ parsed = new URL(url)
412
+ } catch {
413
+ throw new Error(`${url} is not a URL`)
414
+ }
415
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
416
+ throw new Error(`${parsed.protocol} is not http or https`)
417
+ }
418
+ const spec = isRecord(init) ? init : {}
419
+ const headers: Record<string, string> = {}
420
+ if (isRecord(spec.headers)) {
421
+ for (const [key, value] of Object.entries(spec.headers)) {
422
+ if (typeof value === 'string') headers[key] = value
423
+ }
424
+ }
425
+ if (spec.body !== undefined && typeof spec.body !== 'string') throw new Error('body is text')
426
+ const response = await fetchImpl(parsed, {
427
+ method: typeof spec.method === 'string' ? spec.method : 'GET',
428
+ headers,
429
+ ...(typeof spec.body === 'string' ? { body: spec.body } : {}),
430
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
431
+ })
432
+ const bytes = Buffer.from(await response.arrayBuffer())
433
+ const answered: Record<string, string> = {}
434
+ response.headers.forEach((value, key) => {
435
+ answered[key.toLowerCase()] = value
436
+ })
437
+ return {
438
+ status: response.status,
439
+ ok: response.ok,
440
+ headers: answered,
441
+ text: bytes.subarray(0, MAX_CAPABILITY_BYTES).toString('utf8'),
442
+ }
443
+ }
444
+
445
+ return {
446
+ endProcesses() {
447
+ for (const child of children) {
448
+ try {
449
+ child.kill('SIGKILL')
450
+ } catch {
451
+ // Already gone.
452
+ }
453
+ }
454
+ children.clear()
455
+ },
456
+ async call(noun, method, args) {
457
+ switch (`${noun}.${method}`) {
458
+ case 'fs.read':
459
+ return fs.read(args)
460
+ case 'fs.exists':
461
+ return fs.exists(args)
462
+ case 'fs.stat':
463
+ return fs.stat(args)
464
+ case 'fs.list':
465
+ return fs.list(args)
466
+ case 'store.get':
467
+ return store.get(args)
468
+ case 'store.set':
469
+ return store.set(args)
470
+ case 'store.delete':
471
+ return store.delete(args)
472
+ case 'store.keys':
473
+ return store.keys()
474
+ case 'process.run':
475
+ return run(args)
476
+ case 'http.fetch':
477
+ return httpFetch(args)
478
+ case 'env.get': {
479
+ const name = args[0]
480
+ if (typeof name !== 'string' || !options.envNames.includes(name)) {
481
+ throw new Error(
482
+ '$.env.get answers only a variable whose name the module writes out as a string literal',
483
+ )
484
+ }
485
+ return environment[name]
486
+ }
487
+ case 'ui.log': {
488
+ const text = args[0]
489
+ options.log.info('Plugin hooks module log', {
490
+ 'namzu.plugin.name': options.pluginName,
491
+ 'namzu.hook_module.text': typeof text === 'string' ? text.slice(0, 2000) : String(text),
492
+ })
493
+ return undefined
494
+ }
495
+ default:
496
+ throw new Error(`$.${noun}.${method} is not available in Namzu`)
497
+ }
498
+ },
499
+ }
500
+ }