@pluginfinity/engine 0.2.0 → 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/hooks.js CHANGED
@@ -44,25 +44,56 @@ const targetHooks = (target, id, config) => {
44
44
  const hookScripts = (events) => [...new Set(events.flatMap((event) => event.entries.flatMap((entry) => "script" in entry ? [entry.script] : [])))];
45
45
  const COMMAND_FILE = /\$\{PLUGIN_ROOT\}\/([^\s"'`;|&<>()$]+)/g;
46
46
  /**
47
+ * Every file a command names as `${PLUGIN_ROOT}/<path>`, in order.
48
+ *
49
+ * @public
50
+ */
51
+ const commandFiles = (command) => [...command.matchAll(COMMAND_FILE)].map((match) => match[1] ?? "");
52
+ /**
47
53
  * Every file the given events' `command` entries name as
48
54
  * `${PLUGIN_ROOT}/<path>`, so the build can ship and check them as it does
49
55
  * `script` paths.
50
56
  *
51
57
  * @public
52
58
  */
53
- const hookCommandFiles = (events) => [...new Set(events.flatMap((event) => event.entries.flatMap((entry) => "command" in entry ? [...entry.command.matchAll(COMMAND_FILE)].map((match) => match[1] ?? "") : [])))];
59
+ const hookCommandFiles = (events) => [...new Set(events.flatMap((event) => event.entries.flatMap((entry) => "command" in entry ? commandFiles(entry.command) : [])))];
54
60
  const shellQuote = (word) => /^[A-Za-z0-9_\-./=:@%+,]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
55
61
  const PLUGIN_ROOT = `\${PLUGIN_ROOT}`;
56
62
  const SAFE_PATH = /^[A-Za-z0-9_\-./@%+,=:]+$/;
57
63
  /**
64
+ * The environment every hook entry runs with: the event the library reads
65
+ * (camelCase Copilot payloads carry no `hook_event_name`), `"1"` for
66
+ * `PLUGINFINITY_FAIL_CLOSED` when the entry sets `failClosed`, and the
67
+ * matcher when one is given.
68
+ *
69
+ * @public
70
+ */
71
+ const entryEnv = (event, entry, matcher) => ({
72
+ PLUGINFINITY_EVENT: event,
73
+ ...entry.failClosed === true ? { PLUGINFINITY_FAIL_CLOSED: "1" } : {},
74
+ ...matcher === void 0 ? {} : { PLUGINFINITY_MATCHER: matcher }
75
+ });
76
+ const quoteValue = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
77
+ /**
78
+ * An env as a shell prefix, `K='V' ` per pair: every value single-quoted, and
79
+ * empty for an empty env.
80
+ *
81
+ * @public
82
+ */
83
+ const shellEnvPrefix = (env) => Object.entries(env).map(([key, value]) => `${key}=${quoteValue(value)} `).join("");
84
+ /**
58
85
  * The shell command a hook entry runs on a target: a `script` through `bash`
59
86
  * (or executed directly under `scripts.invoke: "exec"`) at the target's
60
87
  * plugin root, or a `command` with `${PLUGIN_ROOT}` spelled the target's way.
61
88
  *
62
89
  * @public
63
90
  */
64
- const hookCommand = (entry, root, invoke) => {
65
- if ("command" in entry) return entry.command.replaceAll(PLUGIN_ROOT, root);
91
+ const hookCommand = (entry, root, invoke, env = {}) => {
92
+ const pairs = Object.entries(env).map(([key, value]) => `${key}=${quoteValue(value)}`);
93
+ if ("command" in entry) {
94
+ const command = entry.command.replaceAll(PLUGIN_ROOT, root);
95
+ return pairs.length === 0 ? command : `${pairs.map((pair) => `export ${pair};`).join(" ")} ${command}`;
96
+ }
66
97
  const path = SAFE_PATH.test(entry.script) ? `"${root}/${entry.script}"` : `"${root}"/${shellQuote(entry.script)}`;
67
98
  const args = (entry.args ?? []).map(shellQuote);
68
99
  return [...invoke === "bash" ? ["bash", path] : [path], ...args].join(" ");
@@ -75,9 +106,19 @@ const hookCommand = (entry, root, invoke) => {
75
106
  *
76
107
  * @public
77
108
  */
78
- const hookExec = (entry, root, invoke) => {
109
+ const hookExec = (entry, root, invoke, env = {}) => {
79
110
  const path = `${root}/${entry.script}`;
80
111
  const args = [...entry.args ?? []];
112
+ const pairs = Object.entries(env).map(([key, value]) => `${key}=${value}`);
113
+ if (pairs.length > 0) return {
114
+ command: "env",
115
+ args: [
116
+ ...pairs,
117
+ ...invoke === "bash" ? ["bash"] : [],
118
+ path,
119
+ ...args
120
+ ]
121
+ };
81
122
  return invoke === "bash" ? {
82
123
  command: "bash",
83
124
  args: [path, ...args]
@@ -86,23 +127,75 @@ const hookExec = (entry, root, invoke) => {
86
127
  args
87
128
  };
88
129
  };
130
+ const EXACT_LIST = /^[A-Za-z0-9_| ,-]*$/;
131
+ /**
132
+ * How a host that ignores the SessionStart matcher is told a matcher: a host
133
+ * names a fresh session's source `new` where Claude says `startup`, so a
134
+ * matcher that matches `startup` must match `new` too.
135
+ *
136
+ * An exact list holding `startup` gains `new` right after it (`startup|resume`
137
+ * becomes `startup|new|resume`); one that already holds `new`, an empty or `*`
138
+ * matcher and any matcher not matching `startup` stay as written. A regex
139
+ * that matches `startup` but not `new` also stays as written, reported as
140
+ * `unwidened` so the build can note it. The regex is tried as a JavaScript
141
+ * `RegExp` while the hook library matches with `grep -E`, so exotic syntax
142
+ * may differ.
143
+ *
144
+ * @public
145
+ */
146
+ const sessionStartMatcher = (matcher) => {
147
+ const same = {
148
+ matcher,
149
+ widened: false,
150
+ unwidened: false
151
+ };
152
+ if (matcher === "" || matcher === "*") return same;
153
+ if (EXACT_LIST.test(matcher)) {
154
+ const items = matcher.split("|");
155
+ const at = items.indexOf("startup");
156
+ if (at === -1 || items.includes("new")) return same;
157
+ items.splice(at + 1, 0, "new");
158
+ return {
159
+ matcher: items.join("|"),
160
+ widened: true,
161
+ unwidened: false
162
+ };
163
+ }
164
+ try {
165
+ const regex = new RegExp(matcher);
166
+ return {
167
+ ...same,
168
+ unwidened: regex.test("startup") && !regex.test("new")
169
+ };
170
+ } catch {
171
+ return same;
172
+ }
173
+ };
174
+ /**
175
+ * Whether a host that ignores matchers on `event` (`ignored` is its list) is
176
+ * given a widened SessionStart matcher.
177
+ *
178
+ * @public
179
+ */
180
+ const widensSessionStart = (ignored, event) => event === "SessionStart" && ignored.includes(event);
181
+ const runtimeMatcher = (ignored, event, entry) => ignored.includes(event) ? entry.matcher !== void 0 && widensSessionStart(ignored, event) ? sessionStartMatcher(entry.matcher).matcher : entry.matcher : void 0;
89
182
  const FORMATS = {
90
- "claude-hooks-json": (events, command, exec) => ({ hooks: Object.fromEntries(events.map(({ name, entries }) => [name, entries.map((entry) => ({
91
- ...entry.matcher === void 0 ? {} : { matcher: entry.matcher },
183
+ "claude-hooks-json": (events, command, exec, ignored) => ({ hooks: Object.fromEntries(events.map(({ event, name, entries }) => [name, entries.map((entry) => ({
184
+ ...entry.matcher === void 0 || ignored.includes(event) ? {} : { matcher: entry.matcher },
92
185
  hooks: [{
93
186
  type: "command",
94
- ..."script" in entry ? exec(entry) : { command: command(entry) },
187
+ ..."script" in entry ? exec(entry, entryEnv(event, entry, runtimeMatcher(ignored, event, entry))) : { command: command(entry, entryEnv(event, entry, runtimeMatcher(ignored, event, entry))) },
95
188
  ...entry.timeout === void 0 ? {} : { timeout: entry.timeout }
96
189
  }]
97
190
  }))])) }),
98
- "copilot-hooks-v1": (events, command) => ({
191
+ "copilot-hooks-v1": (events, command, _exec, ignored) => ({
99
192
  version: 1,
100
193
  hooks: Object.fromEntries(events.map(({ event, name, entries }) => [name, entries.map((entry) => ({
101
194
  type: "command",
102
195
  bash: command(entry),
103
- ...entry.matcher === void 0 ? {} : { matcher: entry.matcher },
196
+ ...entry.matcher === void 0 || ignored.includes(event) ? {} : { matcher: entry.matcher },
104
197
  ...entry.timeout === void 0 ? {} : { timeoutSec: entry.timeout },
105
- env: { PLUGINFINITY_EVENT: event }
198
+ env: entryEnv(event, entry, runtimeMatcher(ignored, event, entry))
106
199
  }))]))
107
200
  })
108
201
  };
@@ -116,8 +209,8 @@ const renderHooks = (target, events, invoke) => {
116
209
  if (events.length === 0) return void 0;
117
210
  const root = target.pluginRoot.hooks;
118
211
  if (typeof root !== "string") throw new Error(`target has no plugin-root spelling for hook commands: ${root.note}`);
119
- return `${JSON.stringify(FORMATS[target.hooks.format](events, (entry) => hookCommand(entry, root, invoke), (entry) => hookExec(entry, root, invoke)), null, " ")}\n`;
212
+ return `${JSON.stringify(FORMATS[target.hooks.format](events, (entry, env) => hookCommand(entry, root, invoke, env), (entry, env) => hookExec(entry, root, invoke, env), target.hooks.matcherIgnored), null, " ")}\n`;
120
213
  };
121
214
 
122
215
  //#endregion
123
- export { hookCommand, hookCommandFiles, hookExec, hookScripts, renderHooks, targetHooks };
216
+ export { commandFiles, entryEnv, hookCommand, hookCommandFiles, hookExec, hookScripts, renderHooks, sessionStartMatcher, shellEnvPrefix, targetHooks, widensSessionStart };