rosetack 0.1.0 → 0.1.2

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 (52) hide show
  1. package/deploy/k8s/rosetack.yaml +107 -0
  2. package/dist-cli/compiler.mjs +2783 -0
  3. package/dist-cli/edge.mjs +332 -0
  4. package/dist-cli/rosetack.mjs +4230 -0
  5. package/dist-cli/runtime.mjs +703 -0
  6. package/dist-cli/test.mjs +3202 -0
  7. package/pack.mjs +49 -0
  8. package/package.json +25 -7
  9. package/src/FRAMEWORK_VERSION +1 -1
  10. package/src/cli/edge.ts +67 -25
  11. package/src/cli/index.ts +858 -94
  12. package/src/cli/prompt.ts +127 -0
  13. package/src/cli/shell.ts +133 -30
  14. package/src/cli/test.ts +400 -0
  15. package/src/compiler/errors.ts +74 -0
  16. package/src/compiler/index.ts +1955 -264
  17. package/src/runtime/index.ts +465 -66
  18. package/src/types/rosetack.d.ts +151 -0
  19. package/.github/workflows/ci.yml +0 -72
  20. package/.github/workflows/release.yml +0 -122
  21. package/benchmark.ts +0 -227
  22. package/example/public/favicon.ico +0 -0
  23. package/example/public/logo.svg +0 -148
  24. package/example/public/rose-mark-black.png +0 -0
  25. package/example/public/rose-mark.png +0 -0
  26. package/example/public/rose-mono.png +0 -0
  27. package/example/rosetack.config.js +0 -10
  28. package/example/src/locales/en.json +0 -8
  29. package/example/src/locales/zh.json +0 -8
  30. package/example/src/pages/404.rose +0 -15
  31. package/example/src/pages/500.rose +0 -10
  32. package/example/src/pages/[lang]/about.rose +0 -40
  33. package/example/src/pages/_layout.rose +0 -33
  34. package/example/src/pages/_middleware.rose +0 -37
  35. package/example/src/pages/about.rose +0 -67
  36. package/example/src/pages/admin.rose +0 -27
  37. package/example/src/pages/api/hello.rose +0 -19
  38. package/example/src/pages/api/login.rose +0 -55
  39. package/example/src/pages/api/posts.rose +0 -80
  40. package/example/src/pages/api/secret.rose +0 -14
  41. package/example/src/pages/blog/[id].rose +0 -25
  42. package/example/src/pages/broken.rose +0 -16
  43. package/example/src/pages/fresh.rose +0 -22
  44. package/example/src/pages/garden.rose +0 -27
  45. package/example/src/pages/index.rose +0 -84
  46. package/example/src/pages/sign.rose +0 -45
  47. package/example/src/pages/thorn.rose +0 -23
  48. package/example/src/pages/vault.rose +0 -14
  49. package/go.mod +0 -3
  50. package/main.go +0 -470
  51. package/tools/release-notes.mjs +0 -113
  52. package/tsconfig.json +0 -17
@@ -0,0 +1,400 @@
1
+ /**
2
+ * rosetack/test - the public testing surface.
3
+ *
4
+ * The framework's own suites proved the pipeline; this module lets a PROJECT
5
+ * prove its own. Two halves, one entry point:
6
+ *
7
+ * const c = await test('src/components/Counter.rose', { props: { start: 5 } });
8
+ * const r = await c.get(); // the server half: rendered HTML + state
9
+ * r.html.includes('5');
10
+ * const after = await c.post({ name: 'Ada' }); // a server action / form POST
11
+ *
12
+ * const dom = new JSDOM('<!DOCTYPE html><html><body><div id="app"></div></body></html>');
13
+ * const p = await test('src/pages/sign.rose', { dom }).then((a) => a.mount());
14
+ * await p.click('button'); // a real event -> fine-grained patch
15
+ * p.text('p');
16
+ * p.requestCount(); // the zero-request story, asserted
17
+ *
18
+ * The design rule: NO second implementation of anything. The
19
+ * harness compiles a throwaway project with the SAME compiler the app uses,
20
+ * then drives the SAME server bundle and client bundle the app ships. There
21
+ * is nothing here that can pass while the real app fails, because there is
22
+ * nothing here that is not the real app.
23
+ *
24
+ * A `.rose` component is not independently renderable in rosetack's
25
+ * architecture - it compiles INTO the app's bundles - so a component test
26
+ * builds the project it lives in with one synthesized page that renders it
27
+ * with the given props. That page is the only thing added; every other route
28
+ * of the app still exists, so navigation and api routes are testable too.
29
+ *
30
+ * Vitest/jest compatible: every entry point is an async function returning
31
+ * plain data. No test-runner dependency, no globals beyond the DOM ones a
32
+ * browser has (and those are grafted from the window `mount()` runs in, so
33
+ * jsdom, happy-dom and vitest's jsdom environment all work unchanged).
34
+ */
35
+
36
+ import * as fs from 'fs';
37
+ import * as os from 'os';
38
+ import * as path from 'path';
39
+ import { pathToFileURL } from 'url';
40
+ import { buildProject } from '../compiler/index.js';
41
+ import { buildShell } from './shell.js';
42
+
43
+ /** A request the harness can make: headers (cookies included) and a body. */
44
+ export interface TestRequest {
45
+ headers?: Record<string, string>;
46
+ cookies?: Record<string, string>;
47
+ }
48
+
49
+ /** What a render answers: the page the server would have sent, in pieces. */
50
+ export interface TestResult {
51
+ status: number;
52
+ /** the route's own HTML (what lands inside <div id="app">) */
53
+ html: string;
54
+ /** the serialized state, parsed - what the client resumes */
55
+ state: Record<string, unknown>;
56
+ head: string[];
57
+ csr?: boolean;
58
+ lang: string;
59
+ dir: string;
60
+ /** the complete document, byte-identical to what the servers send */
61
+ document: string;
62
+ /** a middleware short-circuit's target, when it redirected */
63
+ redirect?: string;
64
+ }
65
+
66
+ /** The mounted component: a live DOM plus the interactions a user performs. */
67
+ export interface TestHandle {
68
+ /** the pathname this mount is on (what location.pathname reads) */
69
+ route: string;
70
+ document: Document;
71
+ window: Window & typeof globalThis;
72
+ /** textContent of a selector (or of the whole container) */
73
+ text(sel?: string): string;
74
+ /** outerHTML of a selector, or null when it matches nothing */
75
+ html(sel?: string): string | null;
76
+ exists(sel: string): boolean;
77
+ /** dispatch a real click (bubbles, cancelable) and let the handler run */
78
+ click(sel: string): Promise<void>;
79
+ /** set an input's value the way a user typing would */
80
+ fill(sel: string, value: string): void;
81
+ /** submit a form the way the bootstrap does: one POST, in-place adopt */
82
+ submit(formSel?: string, fields?: Record<string, unknown>): Promise<void>;
83
+ /** call a server action by name, from no event at all */
84
+ action(name: string, fields?: Record<string, unknown>): Promise<void>;
85
+ /** client-side navigation to another route of the built app */
86
+ navigate(pathname: string): Promise<void>;
87
+ /** the live state map */
88
+ state(): Record<string, unknown>;
89
+ /** how many requests the client half has made (the zero-request proof) */
90
+ requestCount(): number;
91
+ }
92
+
93
+ export interface TestOptions {
94
+ /** the component's props (`export let`), plain JSON data only */
95
+ props?: Record<string, unknown>;
96
+ /** the route to render for a PAGE target (default: the page's own URL) */
97
+ route?: string;
98
+ /** where to build (default: a fresh temp dir, removed on process exit) */
99
+ dir?: string;
100
+ /** keep the built dir and print its path, for inspecting the artifacts */
101
+ keep?: boolean;
102
+ /**
103
+ * A DOM for `mount()`: a jsdom `new JSDOM()` instance or its `.window`
104
+ * (happy-dom's Window works too - anything with `.window`). Omit it under
105
+ * a jsdom test environment (vitest's `environment: 'jsdom'`), where the
106
+ * globals are already there.
107
+ */
108
+ dom?: unknown;
109
+ }
110
+
111
+ export interface TestApp {
112
+ /** the route under test (the synthesized page's URL, or the page's own) */
113
+ route: string;
114
+ /** the built project's dir (dist is inside it) */
115
+ dir: string;
116
+ /** render a route of the built app (GET) */
117
+ get(pathname?: string, req?: TestRequest): Promise<TestResult>;
118
+ /** render a route with a POST body: runs the server action, re-renders */
119
+ post(fields?: Record<string, unknown>, req?: TestRequest & { route?: string }): Promise<TestResult>;
120
+ /** call an api route: the parsed JSON body (or the raw Response) */
121
+ api(method: string, pathname: string, req?: TestRequest): Promise<{ status: number; body: unknown; headers: Record<string, string> }>;
122
+ /** mount the route in a DOM and drive it like a user would */
123
+ mount(req?: TestRequest): Promise<TestHandle>;
124
+ }
125
+
126
+ // The globals a browser has and a Node test process does not. `mount()` grafts them from
127
+ // the document it parses, exactly like the repo's own client suite does …
128
+ const GRAFTED = ['document', 'Node', 'NodeFilter', 'FormData', 'DOMParser', 'location', 'fetch', 'Event', 'CustomEvent', 'MutationObserver', 'requestAnimationFrame'] as const;
129
+
130
+ /** Absolute path of the project root that owns `file` (the dir holding src/pages). */
131
+ function projectRootOf(file: string): string {
132
+ let dir = path.dirname(path.resolve(file));
133
+ for (;;) {
134
+ if (fs.existsSync(path.join(dir, 'src', 'pages'))) return dir;
135
+ const parent = path.dirname(dir);
136
+ if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
137
+ dir = parent;
138
+ }
139
+ }
140
+
141
+ /** `src/pages/blog/[id].rose` -> `/blog/:id`; `src/pages/index.rose` -> `/`. */
142
+ function routeOf(file: string, root: string): string {
143
+ const rel = path.relative(path.join(root, 'src', 'pages'), path.resolve(file)).replace(/\\/g, '/').replace(/\.rose$/, '');
144
+ if (rel === 'index') return '/';
145
+ const segs = rel.split('/').map((s) => (s.startsWith('[') && s.endsWith(']') ? `:${s.slice(1, -1)}` : s));
146
+ return '/' + segs.join('/');
147
+ }
148
+
149
+ /** A concrete URL for a pattern: `:id` -> 1, `:lang` -> the app's default locale. */
150
+ function concreteRoute(pattern: string, defaultLocale: string | null): string {
151
+ return pattern.split('/').map((s) => (s.startsWith(':') ? (s === ':lang' ? defaultLocale ?? 'en' : '1') : s)).join('/');
152
+ }
153
+
154
+ /** Copy a directory tree, skipping nothing (a test fixture is small). */
155
+ function copyTree(from: string, to: string): void {
156
+ fs.mkdirSync(to, { recursive: true });
157
+ for (const e of fs.readdirSync(from, { withFileTypes: true })) {
158
+ const src = path.join(from, e.name);
159
+ const dst = path.join(to, e.name);
160
+ if (e.isDirectory()) copyTree(src, dst);
161
+ else fs.copyFileSync(src, dst);
162
+ }
163
+ }
164
+
165
+ /** `key={value}` attributes from a props object, as JS literals. */
166
+ function propAttrs(props: Record<string, unknown>): string {
167
+ return Object.entries(props)
168
+ .map(([k, v]) => `${k}={${JSON.stringify(v) ?? 'undefined'}}`)
169
+ .join(' ');
170
+ }
171
+
172
+ let tmpCount = 0;
173
+
174
+ /**
175
+ * Compile `file` into a throwaway project and return a driver over the
176
+ * bundles that build produced. `file` is a `.rose` component
177
+ * (`src/components/**`) or page (`src/pages/**`).
178
+ */
179
+ export async function test(file: string, opts: TestOptions = {}): Promise<TestApp> {
180
+ const target = path.resolve(file);
181
+ if (!fs.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
182
+ const root = projectRootOf(target);
183
+ const rel = path.relative(root, target).replace(/\\/g, '/');
184
+ const isComponent = rel.startsWith('src/components/');
185
+
186
+ // The fixture project: the app's own sources (so every route, component, config and
187
+ // public asset resolves exactly as it does for the app) plus, for a component target …
188
+ const dir = opts.dir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'rosetack-test-'));
189
+ for (const item of ['src', 'public']) {
190
+ const from = path.join(root, item);
191
+ if (fs.existsSync(from)) copyTree(from, path.join(dir, item));
192
+ }
193
+ for (const item of ['rosetack.config.js']) {
194
+ const from = path.join(root, item);
195
+ if (fs.existsSync(from)) fs.copyFileSync(from, path.join(dir, item));
196
+ }
197
+
198
+ let route: string;
199
+ if (isComponent) {
200
+ const specifier = path.relative(path.join(dir, 'src', 'pages'), path.join(dir, rel)).replace(/\\/g, '/');
201
+ const attrs = propAttrs(opts.props ?? {});
202
+ const page = `<script>\n import Target from '${specifier}';\n</script>\n\n<template>\n <Target ${attrs} />\n</template>\n`;
203
+ fs.writeFileSync(path.join(dir, 'src', 'pages', '__rosetack_test.rose'), page);
204
+ route = '/__rosetack_test';
205
+ } else {
206
+ route = opts.route ?? routeOf(target, root);
207
+ }
208
+
209
+ const outDir = path.join(dir, 'dist');
210
+ await buildProject(dir, outDir);
211
+
212
+ // The two bundles the app ships - the same ones the servers run. Imported once per test()
213
+ // call: the server module holds module state …
214
+ const serverUrl = pathToFileURL(path.join(outDir, 'server.js')).href;
215
+ const clientUrl = pathToFileURL(path.join(outDir, 'client.js')).href;
216
+ const mod = await import(serverUrl);
217
+ const clientSource = fs.readFileSync(path.join(outDir, 'client.js'), 'utf-8');
218
+ let styles = '';
219
+ try {
220
+ styles = fs.readFileSync(path.join(outDir, 'styles.css'), 'utf-8');
221
+ } catch { /* no component styles: shell styles only */ }
222
+
223
+ if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
224
+ if (!opts.dir && !opts.keep) {
225
+ // a temp fixture is not the developer's to clean up by hand. On exit, not now: the
226
+ // locale packs and chunks below are read from disk while the mounted half runs …
227
+ process.once('exit', () => {
228
+ try {
229
+ fs.rmSync(dir, { recursive: true, force: true });
230
+ } catch { /* the OS temp dir will reap it */ }
231
+ });
232
+ }
233
+
234
+ /** A page result from a rendered page (or a middleware short-circuit). */
235
+ const result = (page: any, redirect?: string): TestResult => ({
236
+ status: page.status ?? 200,
237
+ html: page.html,
238
+ state: page.state ? JSON.parse(page.state) : {},
239
+ head: page.head ?? [],
240
+ csr: page.csr,
241
+ lang: page.lang ?? 'en',
242
+ dir: page.dir ?? '',
243
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? 'en', page.dir ?? ''),
244
+ redirect,
245
+ });
246
+
247
+ /** The Web-standard Request a server would build, for the middleware. */
248
+ const toRequest = (pathname: string, req: TestRequest = {}, body?: FormData) => {
249
+ const headers = new Headers(req.headers ?? {});
250
+ for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append('cookie', `${k}=${v}`);
251
+ return new Request(`http://localhost${pathname}`, { method: body ? 'POST' : 'GET', headers, body });
252
+ };
253
+
254
+ /**
255
+ * One request through the real server pipeline: middleware first (it can
256
+ * short-circuit - a redirect, an auth wall), then the render. This is the
257
+ * order the servers use, so a middleware's effect is visible here or it is
258
+ * not visible at all.
259
+ */
260
+ const request = async (pathname: string, req: TestRequest, body?: FormData): Promise<TestResult> => {
261
+ if (mod.middleware) {
262
+ const mw = await mod.runMiddleware(toRequest(pathname, req, body), body);
263
+ if (mw) return { status: mw.status, html: await mw.text(), state: {}, head: [], lang: 'en', dir: '', document: await mw.text(), redirect: mw.headers.get('location') ?? undefined };
264
+ }
265
+ const page = await mod.renderPage(pathname, body);
266
+ return result(page);
267
+ };
268
+
269
+ // The client half's request counter and fetch proxy: the bundle POSTs to
270
+ // location.pathname like a browser, and the answer is the same document the Node server
271
+ // would send …
272
+ let requests = 0;
273
+ let currentRoute = route;
274
+
275
+ const mount = async (req: TestRequest = {}): Promise<TestHandle> => {
276
+ // The window the bundle will live in: the caller's DOM, or the ambient one under a
277
+ // jsdom test environment.
278
+ const win = ((opts.dom as any)?.window ?? opts.dom ?? globalThis) as any;
279
+ if (!win?.document || !win?.DOMParser) {
280
+ throw new Error('rosetack/test: mount() needs a DOM. Pass one - test("src/components/Counter.rose", { dom: new JSDOM() }) - or run under a jsdom environment.');
281
+ }
282
+ const page = await request(route, req);
283
+
284
+ const doc = win.document;
285
+ const app = doc.getElementById('app') ?? doc.body;
286
+ // reuse the state element across mounts of the same document: a second one would lose
287
+ // getElementById's first-match race and the client would resume the FIRST mount's state
288
+ let stateEl = doc.getElementById('__rosetack_state');
289
+ if (!stateEl) {
290
+ stateEl = doc.createElement('script');
291
+ stateEl.id = '__rosetack_state';
292
+ doc.body.appendChild(stateEl);
293
+ }
294
+ stateEl.textContent = page.state;
295
+ app.innerHTML = page.html;
296
+
297
+ const saved = new Map<string, unknown>();
298
+ for (const key of GRAFTED) {
299
+ saved.set(key, (globalThis as any)[key]);
300
+ (globalThis as any)[key] = win[key] ?? (globalThis as any)[key];
301
+ }
302
+ (globalThis as any).location = { pathname: currentRoute, href: `http://localhost${currentRoute}` };
303
+ (globalThis as any).fetch = async (url: string | URL, init: any) => {
304
+ const pathname = String(url).startsWith('http') ? new URL(String(url)).pathname : String(url);
305
+ // an i18n route's runtime language pack: the same request the browser
306
+ // makes, served from the file this build wrote
307
+ if (pathname.startsWith('/locales/') && pathname.endsWith('.json')) {
308
+ const file = path.join(outDir, pathname.slice(1));
309
+ if (!fs.existsSync(file)) return { ok: false, json: async () => ({}) };
310
+ return { ok: true, json: async () => JSON.parse(fs.readFileSync(file, 'utf-8')) };
311
+ }
312
+ requests++;
313
+ const next = await request(pathname, req, init?.body);
314
+ return { ok: next.status < 400, status: next.status, text: async () => next.document };
315
+ };
316
+
317
+ const client = await import(clientUrl);
318
+ await client.start(app, route, true);
319
+
320
+ const one = (sel?: string): Element | null => (sel ? doc.querySelector(sel) : app);
321
+ const handle: TestHandle = {
322
+ route,
323
+ document: doc,
324
+ window: win,
325
+ text: (sel?: string) => one(sel)?.textContent ?? '',
326
+ html: (sel?: string) => one(sel)?.outerHTML ?? null,
327
+ exists: (sel: string) => !!doc.querySelector(sel),
328
+ click: async (sel: string) => {
329
+ const el = doc.querySelector(sel);
330
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
331
+ el.dispatchEvent(new win.MouseEvent('click', { bubbles: true, cancelable: true }));
332
+ await new Promise((r) => setTimeout(r, 0));
333
+ },
334
+ fill: (sel: string, value: string) => {
335
+ const el = doc.querySelector(sel) as any;
336
+ if (!el) throw new Error(`rosetack/test: no element matches ${sel}`);
337
+ el.value = value;
338
+ },
339
+ submit: async (formSel = 'form', fields?: Record<string, unknown>) => {
340
+ const form = doc.querySelector(formSel) as any;
341
+ if (!form) throw new Error(`rosetack/test: no form matches ${formSel}`);
342
+ const body = new win.FormData(form);
343
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
344
+ await client.postForm(body);
345
+ },
346
+ action: async (name: string, fields?: Record<string, unknown>) => {
347
+ const body = new win.FormData();
348
+ body.append('__action', name);
349
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
350
+ await client.postForm(body);
351
+ },
352
+ navigate: async (pathname: string) => {
353
+ currentRoute = pathname;
354
+ (globalThis as any).location = { pathname, href: `http://localhost${pathname}` };
355
+ await client.start(app, pathname, false);
356
+ },
357
+ state: () => {
358
+ const el = doc.getElementById('__rosetack_state');
359
+ return el?.textContent ? JSON.parse(el.textContent) : {};
360
+ },
361
+ requestCount: () => requests,
362
+ };
363
+ // The graft is intentional and documented: a second mount() re-grafts
364
+ // over the first. `restore` puts the process back the way it was.
365
+ (handle as any).restore = () => { for (const [k, v] of saved) (globalThis as any)[k] = v; };
366
+ return handle;
367
+ };
368
+
369
+ return {
370
+ route,
371
+ dir,
372
+ get: async (pathname = route, req?: TestRequest) => request(pathname, req ?? {}),
373
+ post: async (fields?: Record<string, unknown>, req: TestRequest & { route?: string } = {}) => {
374
+ const pathname = req.route ?? route;
375
+ const body = new FormData();
376
+ for (const [k, v] of Object.entries(fields ?? {})) body.append(k, String(v));
377
+ return request(pathname, req, body);
378
+ },
379
+ api: async (method: string, pathname: string, req: TestRequest = {}) => {
380
+ // the middleware runs first here too - the servers do, and an api
381
+ // route's auth usually lives in it
382
+ if (mod.middleware) {
383
+ const mw = await mod.runMiddleware(toRequest(pathname, req));
384
+ if (mw) return { status: mw.status, body: await mw.text(), headers: { location: mw.headers.get('location') ?? '' } };
385
+ }
386
+ const res = await mod.handleApi(method, pathname, toRequest(pathname, req));
387
+ const text = await res.text();
388
+ let body: unknown = text;
389
+ try {
390
+ body = JSON.parse(text);
391
+ } catch { /* not JSON: hand back the raw text */ }
392
+ const headers: Record<string, string> = {};
393
+ res.headers.forEach((v: string, k: string) => { headers[k] = v; });
394
+ return { status: res.status, body, headers };
395
+ },
396
+ mount,
397
+ };
398
+ }
399
+
400
+ export default test;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A compiler error shaped for its reader - who is as often an AI agent as a
3
+ * human. Every failure the compiler throws on purpose carries:
4
+ *
5
+ * code a stable identifier (E-EXPORT, E-TEMPLATE, ...) an agent can
6
+ * branch on and a human can grep across a build log
7
+ * file the .rose file (or directory) at fault
8
+ * line the line inside it, when the compiler knows the position
9
+ * hint the fix, in one sentence
10
+ *
11
+ * `rosetack build --json` prints these as a JSON envelope on stdout, so an
12
+ * agent can parse the failure and patch the file without scraping prose.
13
+ * The human output prints the message and the hint. Errors that are NOT
14
+ * RoseErrors (a crash inside a plugin's own code, a framework bug) keep
15
+ * their stack: those are not the developer's to fix from a code alone.
16
+ */
17
+
18
+ export interface RoseErrorInfo {
19
+ code: string;
20
+ file?: string;
21
+ line?: number;
22
+ message: string;
23
+ hint?: string;
24
+ }
25
+
26
+ export class RoseError extends Error {
27
+ readonly code: string;
28
+ readonly file?: string;
29
+ readonly line?: number;
30
+ readonly hint?: string;
31
+
32
+ constructor(code: string, message: string, opts: { file?: string; line?: number; hint?: string } = {}) {
33
+ super(message);
34
+ this.name = 'RoseError';
35
+ this.code = code;
36
+ this.file = opts.file;
37
+ this.line = opts.line;
38
+ this.hint = opts.hint;
39
+ }
40
+
41
+ info(): RoseErrorInfo {
42
+ // code -> file -> line -> message -> hint: the order the prompt doc
43
+ // documents, so a reader parsing the envelope finds the location first
44
+ const info = { code: this.code } as RoseErrorInfo;
45
+ if (this.file !== undefined) info.file = this.file;
46
+ if (this.line !== undefined) info.line = this.line;
47
+ info.message = this.message;
48
+ if (this.hint !== undefined) info.hint = this.hint;
49
+ return info;
50
+ }
51
+ }
52
+
53
+ /** The 1-based line of `index` inside `src`. */
54
+ export function lineOf(src: string, index: number): number {
55
+ let line = 1;
56
+ const end = Math.min(index, src.length);
57
+ for (let i = 0; i < end; i++) {
58
+ if (src[i] === '\n') line++;
59
+ }
60
+ return line;
61
+ }
62
+
63
+ /** The line of a regex match inside `src` - undefined when there is no match
64
+ * (the position is optional on a match array, and the call sites that have
65
+ * one always matched). */
66
+ export function lineAt(src: string, match?: RegExpMatchArray | null): number | undefined {
67
+ return match && match.index !== undefined ? lineOf(src, match.index) : undefined;
68
+ }
69
+
70
+ /** Shape any thrown value into the info object the --json envelope prints. */
71
+ export function errorInfo(err: unknown): RoseErrorInfo {
72
+ if (err instanceof RoseError) return err.info();
73
+ return { code: 'E-UNKNOWN', message: err instanceof Error ? err.message : String(err) };
74
+ }