@willbooster/shared-lib 10.8.0 → 10.9.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.
package/dist/error.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";const e=require("./sleep.cjs");function t(e){return e instanceof Error?e:Error(typeof e==`string`?e:n(()=>JSON.stringify(e))??n(()=>String(e)))}function n(e){try{return e()}catch{}}function r(e){try{return e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function i(e){try{return await e()}catch{}}async function a(e){try{return await e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function o(t,{beforeRetry:n,handleError:r,retryCount:i=3,retryLogger:a,shouldRetry:o,sleepMilliseconds:s=0,updateSleepMilliseconds:c}={}){let l=0;for(;;)try{return await t(l)}catch(t){if(await r?.(t),l++,l>=i||o&&!o(t))throw t;s>0&&await e.sleep(s),c&&(s=c(s)),a?.(`Retry due to: ${t}
1
+ "use strict";const e=require("./sleep.cjs");function t(e){return e instanceof Error?e:Error(typeof e==`string`?e:n(()=>JSON.stringify(e))??n(()=>String(e)))}function n(e){try{return e()}catch{}}function r(e){try{return e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function i(e){try{return await e()}catch{}}async function a(e){try{return await e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function o(t,{beforeRetry:n,handleError:r,retryCount:i=3,retryLogger:a,shouldRetry:o,getSleepMilliseconds:s,sleepMilliseconds:c=0,updateSleepMilliseconds:l}={}){let u=0;for(;;)try{return await t(u)}catch(t){if(await r?.(t),u++,u>=i||o&&!o(t))throw t;let d=s?.(t,c)??c;d>0&&await e.sleep(d),l&&(c=l(c)),a?.(`Retry due to: ${t}
2
2
  ${t instanceof Error?`---
3
3
  `+(t.stack??``):``}`),await n?.(t)}}exports.errorify=t,exports.ignoreEnoent=r,exports.ignoreEnoentAsync=a,exports.ignoreError=n,exports.ignoreErrorAsync=i,exports.withRetry=o;
4
4
  //# sourceMappingURL=error.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"error.cjs","names":["sleep"],"sources":["../src/error.ts"],"sourcesContent":["import { sleep } from './sleep.js';\n\n/**\n * Convert an object to an error.\n * @param obj The object to convert.\n */\nexport function errorify(obj: unknown): Error {\n if (obj instanceof Error) return obj;\n if (typeof obj === 'string') return new Error(obj);\n // `JSON.stringify` answers `undefined` for `undefined`, a symbol and a function, and throws\n // on a bigint or a cycle; `new Error(undefined)` has an empty message, which would drop the\n // only diagnostic a caller has about such a thrown value. Neither representation may throw\n // out of here: this runs in a catch block, where it would replace the error it converts.\n return new Error(ignoreError(() => JSON.stringify(obj)) ?? ignoreError(() => String(obj)));\n}\n\nexport function ignoreError<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n // do nothing\n }\n}\n\nexport function ignoreEnoent<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport async function ignoreErrorAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch {\n // do nothing\n }\n}\n\nexport async function ignoreEnoentAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport interface RetryOptions {\n beforeRetry?: (error: unknown) => Promise<void>;\n handleError?: (error: unknown) => Promise<void>;\n /**\n * The maximum number of total attempts, including the initial attempt.\n * For example, `retryCount: 3` runs the function at most 3 times: 1 initial attempt and up to 2 retries.\n */\n retryCount?: number;\n retryLogger?: (message: string) => void;\n shouldRetry?: (error: unknown) => boolean;\n sleepMilliseconds?: number;\n updateSleepMilliseconds?: (sleepMilliseconds: number) => number;\n}\n\n/**\n * Retry the given function.\n * @param func The function to retry.\n * @param beforeRetry The function to call immediately before retrying.\n * @param handleError The function to call when an error occurs.\n * @param retryCount The maximum number of total attempts, including the initial attempt.\n * @param retryLogger The function to log retrying.\n * @param sleepMilliseconds The number of milliseconds to sleep before retrying.\n * @param updateSleepMilliseconds The function to update sleep milliseconds after each retry.\n */\nexport async function withRetry<T>(\n func: (failedCount: number) => T | Promise<T>,\n {\n beforeRetry,\n handleError,\n retryCount = 3,\n retryLogger,\n shouldRetry,\n sleepMilliseconds = 0,\n updateSleepMilliseconds,\n }: RetryOptions = {}\n): Promise<T> {\n let failedCount = 0;\n for (;;) {\n try {\n return await func(failedCount);\n } catch (error) {\n await handleError?.(error);\n failedCount++;\n if (failedCount >= retryCount) {\n throw error;\n }\n if (shouldRetry && !shouldRetry(error)) {\n throw error;\n }\n if (sleepMilliseconds > 0) {\n await sleep(sleepMilliseconds);\n }\n if (updateSleepMilliseconds) {\n sleepMilliseconds = updateSleepMilliseconds(sleepMilliseconds);\n }\n retryLogger?.(`Retry due to: ${error}\n${error instanceof Error ? '---\\n' + (error.stack ?? '') : ''}`);\n await beforeRetry?.(error);\n }\n }\n}\n"],"mappings":"4CAMA,SAAgB,EAAS,EAAqB,CAO5C,OANI,aAAe,MAAc,EACO,MAApC,OAAO,GAAQ,SAA2B,EAK7B,MAAkB,KAAK,UAAU,CAAG,CAAC,GAAK,MAAkB,OAAO,CAAG,CAAC,CALvC,CAMnD,CAEA,SAAgB,EAAe,EAA4B,CACzD,GAAI,CACF,OAAO,EAAG,CACZ,MAAQ,CAER,CACF,CAEA,SAAgB,EAAgB,EAA4B,CAC1D,GAAI,CACF,OAAO,EAAG,CACZ,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CAEA,eAAsB,EAAoB,EAA8C,CACtF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,MAAQ,CAER,CACF,CAEA,eAAsB,EAAqB,EAA8C,CACvF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CA0BA,eAAsB,EACpB,EACA,CACE,cACA,cACA,aAAa,EACb,cACA,cACA,oBAAoB,EACpB,2BACgB,CAAC,EACP,CACZ,IAAI,EAAc,EAClB,OACE,GAAI,CACF,OAAO,MAAM,EAAK,CAAW,CAC/B,OAAS,EAAO,CAMd,GALA,MAAM,IAAc,CAAK,EACzB,IACI,GAAe,GAGf,GAAe,CAAC,EAAY,CAAK,EACnC,MAAM,EAEJ,EAAoB,GACtB,MAAMA,EAAAA,MAAM,CAAiB,EAE3B,IACF,EAAoB,EAAwB,CAAiB,GAE/D,IAAc,iBAAiB,EAAM;EACzC,aAAiB,MAAQ;GAAW,EAAM,OAAS,IAAM,IAAI,EACzD,MAAM,IAAc,CAAK,CAC3B,CAEJ"}
1
+ {"version":3,"file":"error.cjs","names":["sleep"],"sources":["../src/error.ts"],"sourcesContent":["import { sleep } from './sleep.js';\n\n/**\n * Convert an object to an error.\n * @param obj The object to convert.\n */\nexport function errorify(obj: unknown): Error {\n if (obj instanceof Error) return obj;\n if (typeof obj === 'string') return new Error(obj);\n // `JSON.stringify` answers `undefined` for `undefined`, a symbol and a function, and throws\n // on a bigint or a cycle; `new Error(undefined)` has an empty message, which would drop the\n // only diagnostic a caller has about such a thrown value. Neither representation may throw\n // out of here: this runs in a catch block, where it would replace the error it converts.\n return new Error(ignoreError(() => JSON.stringify(obj)) ?? ignoreError(() => String(obj)));\n}\n\nexport function ignoreError<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n // do nothing\n }\n}\n\nexport function ignoreEnoent<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport async function ignoreErrorAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch {\n // do nothing\n }\n}\n\nexport async function ignoreEnoentAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport interface RetryOptions {\n beforeRetry?: (error: unknown) => Promise<void>;\n handleError?: (error: unknown) => Promise<void>;\n /**\n * The maximum number of total attempts, including the initial attempt.\n * For example, `retryCount: 3` runs the function at most 3 times: 1 initial attempt and up to 2 retries.\n */\n retryCount?: number;\n retryLogger?: (message: string) => void;\n shouldRetry?: (error: unknown) => boolean;\n /**\n * Decides how long to wait before retrying after `error`, given the backoff `sleepMilliseconds` it would otherwise wait,\n * e.g. `(error, ms) => Math.max(ms, retryAtOf(error) - Date.now())` to honor a retry time sent by a server.\n * It does not affect the backoff that `updateSleepMilliseconds` advances.\n */\n getSleepMilliseconds?: (error: unknown, sleepMilliseconds: number) => number;\n sleepMilliseconds?: number;\n updateSleepMilliseconds?: (sleepMilliseconds: number) => number;\n}\n\n/**\n * Retry the given function.\n * @param func The function to retry.\n * @param beforeRetry The function to call immediately before retrying.\n * @param handleError The function to call when an error occurs.\n * @param retryCount The maximum number of total attempts, including the initial attempt.\n * @param retryLogger The function to log retrying.\n * @param sleepMilliseconds The number of milliseconds to sleep before retrying.\n * @param updateSleepMilliseconds The function to update sleep milliseconds after each retry.\n */\nexport async function withRetry<T>(\n func: (failedCount: number) => T | Promise<T>,\n {\n beforeRetry,\n handleError,\n retryCount = 3,\n retryLogger,\n shouldRetry,\n getSleepMilliseconds,\n sleepMilliseconds = 0,\n updateSleepMilliseconds,\n }: RetryOptions = {}\n): Promise<T> {\n let failedCount = 0;\n for (;;) {\n try {\n return await func(failedCount);\n } catch (error) {\n await handleError?.(error);\n failedCount++;\n if (failedCount >= retryCount) {\n throw error;\n }\n if (shouldRetry && !shouldRetry(error)) {\n throw error;\n }\n const currentSleepMilliseconds = getSleepMilliseconds?.(error, sleepMilliseconds) ?? sleepMilliseconds;\n if (currentSleepMilliseconds > 0) {\n await sleep(currentSleepMilliseconds);\n }\n if (updateSleepMilliseconds) {\n sleepMilliseconds = updateSleepMilliseconds(sleepMilliseconds);\n }\n retryLogger?.(`Retry due to: ${error}\n${error instanceof Error ? '---\\n' + (error.stack ?? '') : ''}`);\n await beforeRetry?.(error);\n }\n }\n}\n"],"mappings":"4CAMA,SAAgB,EAAS,EAAqB,CAO5C,OANI,aAAe,MAAc,EACO,MAApC,OAAO,GAAQ,SAA2B,EAK7B,MAAkB,KAAK,UAAU,CAAG,CAAC,GAAK,MAAkB,OAAO,CAAG,CAAC,CALvC,CAMnD,CAEA,SAAgB,EAAe,EAA4B,CACzD,GAAI,CACF,OAAO,EAAG,CACZ,MAAQ,CAER,CACF,CAEA,SAAgB,EAAgB,EAA4B,CAC1D,GAAI,CACF,OAAO,EAAG,CACZ,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CAEA,eAAsB,EAAoB,EAA8C,CACtF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,MAAQ,CAER,CACF,CAEA,eAAsB,EAAqB,EAA8C,CACvF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CAgCA,eAAsB,EACpB,EACA,CACE,cACA,cACA,aAAa,EACb,cACA,cACA,uBACA,oBAAoB,EACpB,2BACgB,CAAC,EACP,CACZ,IAAI,EAAc,EAClB,OACE,GAAI,CACF,OAAO,MAAM,EAAK,CAAW,CAC/B,OAAS,EAAO,CAMd,GALA,MAAM,IAAc,CAAK,EACzB,IACI,GAAe,GAGf,GAAe,CAAC,EAAY,CAAK,EACnC,MAAM,EAER,IAAM,EAA2B,IAAuB,EAAO,CAAiB,GAAK,EACjF,EAA2B,GAC7B,MAAMA,EAAAA,MAAM,CAAwB,EAElC,IACF,EAAoB,EAAwB,CAAiB,GAE/D,IAAc,iBAAiB,EAAM;EACzC,aAAiB,MAAQ;GAAW,EAAM,OAAS,IAAM,IAAI,EACzD,MAAM,IAAc,CAAK,CAC3B,CAEJ"}
package/dist/error.d.ts CHANGED
@@ -17,6 +17,12 @@ export interface RetryOptions {
17
17
  retryCount?: number;
18
18
  retryLogger?: (message: string) => void;
19
19
  shouldRetry?: (error: unknown) => boolean;
20
+ /**
21
+ * Decides how long to wait before retrying after `error`, given the backoff `sleepMilliseconds` it would otherwise wait,
22
+ * e.g. `(error, ms) => Math.max(ms, retryAtOf(error) - Date.now())` to honor a retry time sent by a server.
23
+ * It does not affect the backoff that `updateSleepMilliseconds` advances.
24
+ */
25
+ getSleepMilliseconds?: (error: unknown, sleepMilliseconds: number) => number;
20
26
  sleepMilliseconds?: number;
21
27
  updateSleepMilliseconds?: (sleepMilliseconds: number) => number;
22
28
  }
@@ -30,4 +36,4 @@ export interface RetryOptions {
30
36
  * @param sleepMilliseconds The number of milliseconds to sleep before retrying.
31
37
  * @param updateSleepMilliseconds The function to update sleep milliseconds after each retry.
32
38
  */
33
- export declare function withRetry<T>(func: (failedCount: number) => T | Promise<T>, { beforeRetry, handleError, retryCount, retryLogger, shouldRetry, sleepMilliseconds, updateSleepMilliseconds, }?: RetryOptions): Promise<T>;
39
+ export declare function withRetry<T>(func: (failedCount: number) => T | Promise<T>, { beforeRetry, handleError, retryCount, retryLogger, shouldRetry, getSleepMilliseconds, sleepMilliseconds, updateSleepMilliseconds, }?: RetryOptions): Promise<T>;
package/dist/error.js CHANGED
@@ -1,4 +1,4 @@
1
- import{sleep as e}from"./sleep.js";function t(e){return e instanceof Error?e:Error(typeof e==`string`?e:n(()=>JSON.stringify(e))??n(()=>String(e)))}function n(e){try{return e()}catch{}}function r(e){try{return e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function i(e){try{return await e()}catch{}}async function a(e){try{return await e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function o(t,{beforeRetry:n,handleError:r,retryCount:i=3,retryLogger:a,shouldRetry:o,sleepMilliseconds:s=0,updateSleepMilliseconds:c}={}){let l=0;for(;;)try{return await t(l)}catch(t){if(await r?.(t),l++,l>=i||o&&!o(t))throw t;s>0&&await e(s),c&&(s=c(s)),a?.(`Retry due to: ${t}
1
+ import{sleep as e}from"./sleep.js";function t(e){return e instanceof Error?e:Error(typeof e==`string`?e:n(()=>JSON.stringify(e))??n(()=>String(e)))}function n(e){try{return e()}catch{}}function r(e){try{return e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function i(e){try{return await e()}catch{}}async function a(e){try{return await e()}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function o(t,{beforeRetry:n,handleError:r,retryCount:i=3,retryLogger:a,shouldRetry:o,getSleepMilliseconds:s,sleepMilliseconds:c=0,updateSleepMilliseconds:l}={}){let u=0;for(;;)try{return await t(u)}catch(t){if(await r?.(t),u++,u>=i||o&&!o(t))throw t;let d=s?.(t,c)??c;d>0&&await e(d),l&&(c=l(c)),a?.(`Retry due to: ${t}
2
2
  ${t instanceof Error?`---
3
3
  `+(t.stack??``):``}`),await n?.(t)}}export{t as errorify,r as ignoreEnoent,a as ignoreEnoentAsync,n as ignoreError,i as ignoreErrorAsync,o as withRetry};
4
4
  //# sourceMappingURL=error.js.map
package/dist/error.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":[],"sources":["../src/error.ts"],"sourcesContent":["import { sleep } from './sleep.js';\n\n/**\n * Convert an object to an error.\n * @param obj The object to convert.\n */\nexport function errorify(obj: unknown): Error {\n if (obj instanceof Error) return obj;\n if (typeof obj === 'string') return new Error(obj);\n // `JSON.stringify` answers `undefined` for `undefined`, a symbol and a function, and throws\n // on a bigint or a cycle; `new Error(undefined)` has an empty message, which would drop the\n // only diagnostic a caller has about such a thrown value. Neither representation may throw\n // out of here: this runs in a catch block, where it would replace the error it converts.\n return new Error(ignoreError(() => JSON.stringify(obj)) ?? ignoreError(() => String(obj)));\n}\n\nexport function ignoreError<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n // do nothing\n }\n}\n\nexport function ignoreEnoent<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport async function ignoreErrorAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch {\n // do nothing\n }\n}\n\nexport async function ignoreEnoentAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport interface RetryOptions {\n beforeRetry?: (error: unknown) => Promise<void>;\n handleError?: (error: unknown) => Promise<void>;\n /**\n * The maximum number of total attempts, including the initial attempt.\n * For example, `retryCount: 3` runs the function at most 3 times: 1 initial attempt and up to 2 retries.\n */\n retryCount?: number;\n retryLogger?: (message: string) => void;\n shouldRetry?: (error: unknown) => boolean;\n sleepMilliseconds?: number;\n updateSleepMilliseconds?: (sleepMilliseconds: number) => number;\n}\n\n/**\n * Retry the given function.\n * @param func The function to retry.\n * @param beforeRetry The function to call immediately before retrying.\n * @param handleError The function to call when an error occurs.\n * @param retryCount The maximum number of total attempts, including the initial attempt.\n * @param retryLogger The function to log retrying.\n * @param sleepMilliseconds The number of milliseconds to sleep before retrying.\n * @param updateSleepMilliseconds The function to update sleep milliseconds after each retry.\n */\nexport async function withRetry<T>(\n func: (failedCount: number) => T | Promise<T>,\n {\n beforeRetry,\n handleError,\n retryCount = 3,\n retryLogger,\n shouldRetry,\n sleepMilliseconds = 0,\n updateSleepMilliseconds,\n }: RetryOptions = {}\n): Promise<T> {\n let failedCount = 0;\n for (;;) {\n try {\n return await func(failedCount);\n } catch (error) {\n await handleError?.(error);\n failedCount++;\n if (failedCount >= retryCount) {\n throw error;\n }\n if (shouldRetry && !shouldRetry(error)) {\n throw error;\n }\n if (sleepMilliseconds > 0) {\n await sleep(sleepMilliseconds);\n }\n if (updateSleepMilliseconds) {\n sleepMilliseconds = updateSleepMilliseconds(sleepMilliseconds);\n }\n retryLogger?.(`Retry due to: ${error}\n${error instanceof Error ? '---\\n' + (error.stack ?? '') : ''}`);\n await beforeRetry?.(error);\n }\n }\n}\n"],"mappings":"mCAMA,SAAgB,EAAS,EAAqB,CAO5C,OANI,aAAe,MAAc,EACO,MAApC,OAAO,GAAQ,SAA2B,EAK7B,MAAkB,KAAK,UAAU,CAAG,CAAC,GAAK,MAAkB,OAAO,CAAG,CAAC,CALvC,CAMnD,CAEA,SAAgB,EAAe,EAA4B,CACzD,GAAI,CACF,OAAO,EAAG,CACZ,MAAQ,CAER,CACF,CAEA,SAAgB,EAAgB,EAA4B,CAC1D,GAAI,CACF,OAAO,EAAG,CACZ,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CAEA,eAAsB,EAAoB,EAA8C,CACtF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,MAAQ,CAER,CACF,CAEA,eAAsB,EAAqB,EAA8C,CACvF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CA0BA,eAAsB,EACpB,EACA,CACE,cACA,cACA,aAAa,EACb,cACA,cACA,oBAAoB,EACpB,2BACgB,CAAC,EACP,CACZ,IAAI,EAAc,EAClB,OACE,GAAI,CACF,OAAO,MAAM,EAAK,CAAW,CAC/B,OAAS,EAAO,CAMd,GALA,MAAM,IAAc,CAAK,EACzB,IACI,GAAe,GAGf,GAAe,CAAC,EAAY,CAAK,EACnC,MAAM,EAEJ,EAAoB,GACtB,MAAM,EAAM,CAAiB,EAE3B,IACF,EAAoB,EAAwB,CAAiB,GAE/D,IAAc,iBAAiB,EAAM;EACzC,aAAiB,MAAQ;GAAW,EAAM,OAAS,IAAM,IAAI,EACzD,MAAM,IAAc,CAAK,CAC3B,CAEJ"}
1
+ {"version":3,"file":"error.js","names":[],"sources":["../src/error.ts"],"sourcesContent":["import { sleep } from './sleep.js';\n\n/**\n * Convert an object to an error.\n * @param obj The object to convert.\n */\nexport function errorify(obj: unknown): Error {\n if (obj instanceof Error) return obj;\n if (typeof obj === 'string') return new Error(obj);\n // `JSON.stringify` answers `undefined` for `undefined`, a symbol and a function, and throws\n // on a bigint or a cycle; `new Error(undefined)` has an empty message, which would drop the\n // only diagnostic a caller has about such a thrown value. Neither representation may throw\n // out of here: this runs in a catch block, where it would replace the error it converts.\n return new Error(ignoreError(() => JSON.stringify(obj)) ?? ignoreError(() => String(obj)));\n}\n\nexport function ignoreError<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n // do nothing\n }\n}\n\nexport function ignoreEnoent<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport async function ignoreErrorAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch {\n // do nothing\n }\n}\n\nexport async function ignoreEnoentAsync<T>(fn: () => Promise<T>): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {\n return;\n }\n throw error;\n }\n}\n\nexport interface RetryOptions {\n beforeRetry?: (error: unknown) => Promise<void>;\n handleError?: (error: unknown) => Promise<void>;\n /**\n * The maximum number of total attempts, including the initial attempt.\n * For example, `retryCount: 3` runs the function at most 3 times: 1 initial attempt and up to 2 retries.\n */\n retryCount?: number;\n retryLogger?: (message: string) => void;\n shouldRetry?: (error: unknown) => boolean;\n /**\n * Decides how long to wait before retrying after `error`, given the backoff `sleepMilliseconds` it would otherwise wait,\n * e.g. `(error, ms) => Math.max(ms, retryAtOf(error) - Date.now())` to honor a retry time sent by a server.\n * It does not affect the backoff that `updateSleepMilliseconds` advances.\n */\n getSleepMilliseconds?: (error: unknown, sleepMilliseconds: number) => number;\n sleepMilliseconds?: number;\n updateSleepMilliseconds?: (sleepMilliseconds: number) => number;\n}\n\n/**\n * Retry the given function.\n * @param func The function to retry.\n * @param beforeRetry The function to call immediately before retrying.\n * @param handleError The function to call when an error occurs.\n * @param retryCount The maximum number of total attempts, including the initial attempt.\n * @param retryLogger The function to log retrying.\n * @param sleepMilliseconds The number of milliseconds to sleep before retrying.\n * @param updateSleepMilliseconds The function to update sleep milliseconds after each retry.\n */\nexport async function withRetry<T>(\n func: (failedCount: number) => T | Promise<T>,\n {\n beforeRetry,\n handleError,\n retryCount = 3,\n retryLogger,\n shouldRetry,\n getSleepMilliseconds,\n sleepMilliseconds = 0,\n updateSleepMilliseconds,\n }: RetryOptions = {}\n): Promise<T> {\n let failedCount = 0;\n for (;;) {\n try {\n return await func(failedCount);\n } catch (error) {\n await handleError?.(error);\n failedCount++;\n if (failedCount >= retryCount) {\n throw error;\n }\n if (shouldRetry && !shouldRetry(error)) {\n throw error;\n }\n const currentSleepMilliseconds = getSleepMilliseconds?.(error, sleepMilliseconds) ?? sleepMilliseconds;\n if (currentSleepMilliseconds > 0) {\n await sleep(currentSleepMilliseconds);\n }\n if (updateSleepMilliseconds) {\n sleepMilliseconds = updateSleepMilliseconds(sleepMilliseconds);\n }\n retryLogger?.(`Retry due to: ${error}\n${error instanceof Error ? '---\\n' + (error.stack ?? '') : ''}`);\n await beforeRetry?.(error);\n }\n }\n}\n"],"mappings":"mCAMA,SAAgB,EAAS,EAAqB,CAO5C,OANI,aAAe,MAAc,EACO,MAApC,OAAO,GAAQ,SAA2B,EAK7B,MAAkB,KAAK,UAAU,CAAG,CAAC,GAAK,MAAkB,OAAO,CAAG,CAAC,CALvC,CAMnD,CAEA,SAAgB,EAAe,EAA4B,CACzD,GAAI,CACF,OAAO,EAAG,CACZ,MAAQ,CAER,CACF,CAEA,SAAgB,EAAgB,EAA4B,CAC1D,GAAI,CACF,OAAO,EAAG,CACZ,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CAEA,eAAsB,EAAoB,EAA8C,CACtF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,MAAQ,CAER,CACF,CAEA,eAAsB,EAAqB,EAA8C,CACvF,GAAI,CACF,OAAO,MAAM,EAAG,CAClB,OAAS,EAAO,CACd,GAAI,OAAO,GAAU,UAAY,GAAS,SAAU,GAAS,EAAM,OAAS,SAC1E,OAEF,MAAM,CACR,CACF,CAgCA,eAAsB,EACpB,EACA,CACE,cACA,cACA,aAAa,EACb,cACA,cACA,uBACA,oBAAoB,EACpB,2BACgB,CAAC,EACP,CACZ,IAAI,EAAc,EAClB,OACE,GAAI,CACF,OAAO,MAAM,EAAK,CAAW,CAC/B,OAAS,EAAO,CAMd,GALA,MAAM,IAAc,CAAK,EACzB,IACI,GAAe,GAGf,GAAe,CAAC,EAAY,CAAK,EACnC,MAAM,EAER,IAAM,EAA2B,IAAuB,EAAO,CAAiB,GAAK,EACjF,EAA2B,GAC7B,MAAM,EAAM,CAAwB,EAElC,IACF,EAAoB,EAAwB,CAAiB,GAE/D,IAAc,iBAAiB,EAAM;EACzC,aAAiB,MAAQ;GAAW,EAAM,OAAS,IAAM,IAAI,EACzD,MAAM,IAAc,CAAK,CAC3B,CAEJ"}
@@ -1,4 +1,4 @@
1
- "use strict";const e=[{heading:`Why`,requirement:`the problem, with the numbers or observations behind it, and why this approach over the alternatives`},{heading:`Requirements`,requirement:"the requirements the change must satisfy and the guarantees it must keep, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision, which a simpler design may replace); copy the requester's instructions here as given, whether they came from an issue or a conversation, and keep the list when the body is later rewritten unless the requester's instructions changed"},{heading:`Customer Summary`,requirement:`behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation`},{heading:`Technical Summary`,requirement:`decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven`},{heading:`Testing`,requirement:`commands run, tests added, and what was NOT exercised and why`},{heading:`Notes`,requirement:`known limitations, compatibility and migration, follow-up work; delete this section if there is none`}],t="- Requirements section: one line per requirement, taken from the requester's instructions as they were given (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded — ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Record rule: an existing Requirements section is a record, not a description of the diff. Keep its `required` lines as they are, rewriting them only when the requester's instructions changed (then from the updated instructions, dropping a line only when the requester removed it; with no instructions available, keep them unchanged); add a `chosen` line for a new decision, and replace or remove one when the decision it records changed. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.",n=`- Base the PR body on \`.github/pull_request_template.md\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.
1
+ "use strict";const e=[{heading:`Why`,requirement:`the problem, with the numbers or observations behind it, and why this approach over the alternatives`},{heading:`Requirements`,requirement:"the requirements the change must satisfy and the guarantees it must keep as they stand now, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision with the reason that decided it, which a simpler design may replace); state the requester's instructions in the requester's terms, whether they came from an issue or a conversation, and keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of adding one beside it"},{heading:`Customer Summary`,requirement:`behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation`},{heading:`Technical Summary`,requirement:`decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven`},{heading:`Testing`,requirement:`commands run, tests added, and what was NOT exercised and why`},{heading:`Notes`,requirement:`known limitations, compatibility and migration, follow-up work; delete this section if there is none`}],t="- Requirements section: the requirements in force now, one line per requirement, taken from the requester's instructions in the requester's terms (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision with the reason that decided it, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded — ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Current-state rule: an existing Requirements section records what the requester asked for and what was decided as it stands now; it is neither a description of the diff nor a log of how the request evolved. Keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of appending a line beside it; with no instructions available, keep the requester-derived lines unchanged. Never mark when a line was added (e.g., \"(added)\"), and add a `chosen` line for each new decision. When the current design cannot be understood without the change of direction, state it in one sentence in Notes. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.",n=`- Base the PR body on \`.github/pull_request_template.md\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.
2
2
  - Start the body with \`Close #<n>\` only when the PR resolves an existing issue.\n${t}`,r=[{heading:`Problem`,requirement:`what happens, and what should happen instead`},{heading:`Evidence`,requirement:`reproduction steps, logs, run IDs, or links`},{heading:`Impact`,requirement:`who or what is affected, and how badly`},{heading:`Proposal`,requirement:`the fix you have in mind, and the root cause if known`}],i=[{heading:`Background and goal`,requirement:`the problem being solved, for whom, and what outcome counts as success`},{heading:`Behavior`,requirement:`every user- or caller-observable behavior, including inputs, outputs, error cases, edge cases, and interactions with existing behavior, stated precisely enough that two implementers would build the same thing`},{heading:`Acceptance criteria`,requirement:`checkable conditions (Given/When/Then or an equivalent) that decide whether the implementation is done`},{heading:`Scope and non-goals`,requirement:`what the change covers and what it deliberately leaves out, so an implementer knows where to stop`},{heading:`Design constraints`,requirement:`the data, API, schema, UI, and configuration changes, naming, and the existing code or conventions the implementation must fit — as far as the writer intends to constrain them, with everything else explicitly left to the implementer`},{heading:`Compatibility and migration`,requirement:`what existing data, users, callers, or configurations are affected and how the transition happens`},{heading:`Verification`,requirement:`how the change is tested or demonstrated, including what needs no test and why`},{heading:`Open questions`,requirement:`undecided points, each with its options; empty once the specification is implementable`}];function a(e){return e.map(e=>`- **${e.heading}**: ${e.requirement}`).join(`
3
3
  `)}function o(e){return e.map(e=>`## ${e.heading}\n\n<!-- ${e.requirement.charAt(0).toUpperCase()}${e.requirement.slice(1)}. -->`).join(`
4
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"githubTemplates.cjs","names":[],"sources":["../src/githubTemplates.ts"],"sourcesContent":["/**\n * A section of a PR or issue body: its heading and what the section must state. `requirement`\n * starts lowercase and ends without punctuation, so that it reads both as a placeholder sentence\n * (capitalized, with a period appended) and as a checklist clause after the heading.\n */\nexport interface TemplateSection {\n readonly heading: string;\n readonly requirement: string;\n}\n\n/** Sections of a pull request body, in the order they appear in the PR template. */\nexport const PULL_REQUEST_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Why',\n requirement: 'the problem, with the numbers or observations behind it, and why this approach over the alternatives',\n },\n {\n heading: 'Requirements',\n requirement:\n \"the requirements the change must satisfy and the guarantees it must keep, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision, which a simpler design may replace); copy the requester's instructions here as given, whether they came from an issue or a conversation, and keep the list when the body is later rewritten unless the requester's instructions changed\",\n },\n {\n heading: 'Customer Summary',\n requirement:\n 'behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation',\n },\n {\n heading: 'Technical Summary',\n requirement:\n 'decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven',\n },\n {\n heading: 'Testing',\n requirement: 'commands run, tests added, and what was NOT exercised and why',\n },\n {\n heading: 'Notes',\n requirement: 'known limitations, compatibility and migration, follow-up work; delete this section if there is none',\n },\n];\n\n/**\n * How a tool that writes or rewrites a PR body derives it from the repository's PR template, as\n * markdown bullets for an agent's instructions. Stated once here and rendered by every writer (the\n * generated agent instructions, the PR-drafting skills) so the writers cannot drift apart; the\n * template-less branch lets the same text serve repositories outside the organization.\n */\nconst PULL_REQUEST_TEMPLATE_RULES = `- Base the PR body on \\`.github/pull_request_template.md\\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.\n- Start the body with \\`Close #<n>\\` only when the PR resolves an existing issue.`;\n\n/**\n * How a tool that writes or rewrites a PR body fills the Requirements section of\n * `PULL_REQUEST_SECTIONS`, as markdown bullets for an agent's instructions. Skills that draft PR\n * bodies render this text instead of restating it, so the writers and the reviewers that read the\n * section as the boundary a fix must keep never disagree on what a line means.\n */\nexport const PULL_REQUEST_REQUIREMENTS_RULES = `- Requirements section: one line per requirement, taken from the requester's instructions as they were given (the issue, the conversation that asked for the change), each marked \\`required\\` (asked for, or an existing contract callers depend on) or \\`chosen\\` (your own decision, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write \\`required: not recorded — ask the requester\\` as the only request-derived line (a \\`required\\` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Record rule: an existing Requirements section is a record, not a description of the diff. Keep its \\`required\\` lines as they are, rewriting them only when the requester's instructions changed (then from the updated instructions, dropping a line only when the requester removed it; with no instructions available, keep them unchanged); add a \\`chosen\\` line for a new decision, and replace or remove one when the decision it records changed. A section that merely describes the implementation, or holds only the template's placeholder or a \\`required: not recorded\\` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a \\`required\\` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.`;\n\n/** The complete rules for writing a PR body: the template rules followed by the Requirements rules. */\nexport const PULL_REQUEST_BODY_RULES = `${PULL_REQUEST_TEMPLATE_RULES}\\n${PULL_REQUEST_REQUIREMENTS_RULES}`;\n\n/**\n * How a tool that creates an issue derives it from the repository's issue templates, as markdown\n * bullets for an agent's instructions; shared by the same writers as `PULL_REQUEST_BODY_RULES`.\n * Guidance the templates state in their own placeholder comments (which sections to keep, deleting\n * the comments) is deliberately not repeated here, since the writer reads the template anyway.\n */\nexport const ISSUE_TEMPLATE_RULES = `- Follow the closest template under \\`.github/ISSUE_TEMPLATE/\\`: \\`bug.md\\` for wrong behavior, \\`change.md\\` for anything to build or alter; a question or note fitting neither, or a repository without templates, needs no template.\n- Title: a Conventional Commits prefix for the type that fits the change (\\`feat:\\`, \\`fix:\\`, \\`refactor:\\`, \\`docs:\\`, \\`chore:\\`, ...); when it differs from the template's \\`title\\` prefix, replace the template's type label (\\`t: ...\\`) with the one matching the type.\n- The YAML front matter between the \\`---\\` lines is metadata, not body text: pass its \\`labels\\` via \\`--label\\` and submit only the content below the closing \\`---\\` as the body.`;\n\n/** Sections of a bug report, in the order they appear in the issue template. */\nexport const BUG_ISSUE_SECTIONS: readonly TemplateSection[] = [\n { heading: 'Problem', requirement: 'what happens, and what should happen instead' },\n { heading: 'Evidence', requirement: 'reproduction steps, logs, run IDs, or links' },\n { heading: 'Impact', requirement: 'who or what is affected, and how badly' },\n { heading: 'Proposal', requirement: 'the fix you have in mind, and the root cause if known' },\n];\n\n/**\n * Sections a change specification must settle before a third party can implement it, defined\n * once so that the issue template and any tool that drafts or reviews specifications against\n * these sections cannot drift apart; checklist consumers render it with `renderSectionChecklist`.\n * The first three sections suffice for a small change, so they come first.\n */\nexport const CHANGE_ISSUE_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Background and goal',\n requirement: 'the problem being solved, for whom, and what outcome counts as success',\n },\n {\n heading: 'Behavior',\n requirement:\n 'every user- or caller-observable behavior, including inputs, outputs, error cases, edge cases, and interactions with existing behavior, stated precisely enough that two implementers would build the same thing',\n },\n {\n heading: 'Acceptance criteria',\n requirement:\n 'checkable conditions (Given/When/Then or an equivalent) that decide whether the implementation is done',\n },\n {\n heading: 'Scope and non-goals',\n requirement: 'what the change covers and what it deliberately leaves out, so an implementer knows where to stop',\n },\n {\n heading: 'Design constraints',\n requirement:\n 'the data, API, schema, UI, and configuration changes, naming, and the existing code or conventions the implementation must fit — as far as the writer intends to constrain them, with everything else explicitly left to the implementer',\n },\n {\n heading: 'Compatibility and migration',\n requirement: 'what existing data, users, callers, or configurations are affected and how the transition happens',\n },\n {\n heading: 'Verification',\n requirement: 'how the change is tested or demonstrated, including what needs no test and why',\n },\n {\n heading: 'Open questions',\n requirement: 'undecided points, each with its options; empty once the specification is implementable',\n },\n];\n\n/** Renders sections as markdown bullets (`- **Heading**: requirement`). */\nexport function renderSectionChecklist(sections: readonly TemplateSection[]): string {\n return sections.map((section) => `- **${section.heading}**: ${section.requirement}`).join('\\n');\n}\n\n/** Renders sections as markdown headings, each followed by its requirement as a placeholder comment. */\nexport function renderSectionTemplate(sections: readonly TemplateSection[]): string {\n return sections\n .map(\n (section) =>\n `## ${section.heading}\\n\\n<!-- ${section.requirement.charAt(0).toUpperCase()}${section.requirement.slice(1)}. -->`\n )\n .join('\\n\\n');\n}\n"],"mappings":"aAWA,MAAa,EAAoD,CAC/D,CACE,QAAS,MACT,YAAa,sGACf,EACA,CACE,QAAS,eACT,YACE,6cACJ,EACA,CACE,QAAS,mBACT,YACE,4GACJ,EACA,CACE,QAAS,oBACT,YACE,yKACJ,EACA,CACE,QAAS,UACT,YAAa,+DACf,EACA,CACE,QAAS,QACT,YAAa,sGACf,CACF,EAiBa,EAAkC,6/CAMlC,EAA0B;qFAAmC,IAa7D,EAAiD,CAC5D,CAAE,QAAS,UAAW,YAAa,8CAA+C,EAClF,CAAE,QAAS,WAAY,YAAa,6CAA8C,EAClF,CAAE,QAAS,SAAU,YAAa,wCAAyC,EAC3E,CAAE,QAAS,WAAY,YAAa,uDAAwD,CAC9F,EAQa,EAAoD,CAC/D,CACE,QAAS,sBACT,YAAa,wEACf,EACA,CACE,QAAS,WACT,YACE,kNACJ,EACA,CACE,QAAS,sBACT,YACE,wGACJ,EACA,CACE,QAAS,sBACT,YAAa,mGACf,EACA,CACE,QAAS,qBACT,YACE,0OACJ,EACA,CACE,QAAS,8BACT,YAAa,mGACf,EACA,CACE,QAAS,eACT,YAAa,gFACf,EACA,CACE,QAAS,iBACT,YAAa,wFACf,CACF,EAGA,SAAgB,EAAuB,EAA8C,CACnF,OAAO,EAAS,IAAK,GAAY,OAAO,EAAQ,QAAQ,MAAM,EAAQ,aAAa,CAAC,CAAC,KAAK;CAAI,CAChG,CAGA,SAAgB,EAAsB,EAA8C,CAClF,OAAO,EACJ,IACE,GACC,MAAM,EAAQ,QAAQ,WAAW,EAAQ,YAAY,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,EAAQ,YAAY,MAAM,CAAC,EAAE,MAChH,CAAC,CACA,KAAK;;CAAM,CAChB"}
1
+ {"version":3,"file":"githubTemplates.cjs","names":[],"sources":["../src/githubTemplates.ts"],"sourcesContent":["/**\n * A section of a PR or issue body: its heading and what the section must state. `requirement`\n * starts lowercase and ends without punctuation, so that it reads both as a placeholder sentence\n * (capitalized, with a period appended) and as a checklist clause after the heading.\n */\nexport interface TemplateSection {\n readonly heading: string;\n readonly requirement: string;\n}\n\n/** Sections of a pull request body, in the order they appear in the PR template. */\nexport const PULL_REQUEST_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Why',\n requirement: 'the problem, with the numbers or observations behind it, and why this approach over the alternatives',\n },\n {\n heading: 'Requirements',\n requirement:\n \"the requirements the change must satisfy and the guarantees it must keep as they stand now, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision with the reason that decided it, which a simpler design may replace); state the requester's instructions in the requester's terms, whether they came from an issue or a conversation, and keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of adding one beside it\",\n },\n {\n heading: 'Customer Summary',\n requirement:\n 'behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation',\n },\n {\n heading: 'Technical Summary',\n requirement:\n 'decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven',\n },\n {\n heading: 'Testing',\n requirement: 'commands run, tests added, and what was NOT exercised and why',\n },\n {\n heading: 'Notes',\n requirement: 'known limitations, compatibility and migration, follow-up work; delete this section if there is none',\n },\n];\n\n/**\n * How a tool that writes or rewrites a PR body derives it from the repository's PR template, as\n * markdown bullets for an agent's instructions. Stated once here and rendered by every writer (the\n * generated agent instructions, the PR-drafting skills) so the writers cannot drift apart; the\n * template-less branch lets the same text serve repositories outside the organization.\n */\nconst PULL_REQUEST_TEMPLATE_RULES = `- Base the PR body on \\`.github/pull_request_template.md\\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.\n- Start the body with \\`Close #<n>\\` only when the PR resolves an existing issue.`;\n\n/**\n * How a tool that writes or rewrites a PR body fills the Requirements section of\n * `PULL_REQUEST_SECTIONS`, as markdown bullets for an agent's instructions. Skills that draft PR\n * bodies render this text instead of restating it, so the writers and the reviewers that read the\n * section as the boundary a fix must keep never disagree on what a line means.\n */\nexport const PULL_REQUEST_REQUIREMENTS_RULES = `- Requirements section: the requirements in force now, one line per requirement, taken from the requester's instructions in the requester's terms (the issue, the conversation that asked for the change), each marked \\`required\\` (asked for, or an existing contract callers depend on) or \\`chosen\\` (your own decision with the reason that decided it, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write \\`required: not recorded — ask the requester\\` as the only request-derived line (a \\`required\\` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Current-state rule: an existing Requirements section records what the requester asked for and what was decided as it stands now; it is neither a description of the diff nor a log of how the request evolved. Keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of appending a line beside it; with no instructions available, keep the requester-derived lines unchanged. Never mark when a line was added (e.g., \"(added)\"), and add a \\`chosen\\` line for each new decision. When the current design cannot be understood without the change of direction, state it in one sentence in Notes. A section that merely describes the implementation, or holds only the template's placeholder or a \\`required: not recorded\\` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a \\`required\\` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.`;\n\n/** The complete rules for writing a PR body: the template rules followed by the Requirements rules. */\nexport const PULL_REQUEST_BODY_RULES = `${PULL_REQUEST_TEMPLATE_RULES}\\n${PULL_REQUEST_REQUIREMENTS_RULES}`;\n\n/**\n * How a tool that creates an issue derives it from the repository's issue templates, as markdown\n * bullets for an agent's instructions; shared by the same writers as `PULL_REQUEST_BODY_RULES`.\n * Guidance the templates state in their own placeholder comments (which sections to keep, deleting\n * the comments) is deliberately not repeated here, since the writer reads the template anyway.\n */\nexport const ISSUE_TEMPLATE_RULES = `- Follow the closest template under \\`.github/ISSUE_TEMPLATE/\\`: \\`bug.md\\` for wrong behavior, \\`change.md\\` for anything to build or alter; a question or note fitting neither, or a repository without templates, needs no template.\n- Title: a Conventional Commits prefix for the type that fits the change (\\`feat:\\`, \\`fix:\\`, \\`refactor:\\`, \\`docs:\\`, \\`chore:\\`, ...); when it differs from the template's \\`title\\` prefix, replace the template's type label (\\`t: ...\\`) with the one matching the type.\n- The YAML front matter between the \\`---\\` lines is metadata, not body text: pass its \\`labels\\` via \\`--label\\` and submit only the content below the closing \\`---\\` as the body.`;\n\n/** Sections of a bug report, in the order they appear in the issue template. */\nexport const BUG_ISSUE_SECTIONS: readonly TemplateSection[] = [\n { heading: 'Problem', requirement: 'what happens, and what should happen instead' },\n { heading: 'Evidence', requirement: 'reproduction steps, logs, run IDs, or links' },\n { heading: 'Impact', requirement: 'who or what is affected, and how badly' },\n { heading: 'Proposal', requirement: 'the fix you have in mind, and the root cause if known' },\n];\n\n/**\n * Sections a change specification must settle before a third party can implement it, defined\n * once so that the issue template and any tool that drafts or reviews specifications against\n * these sections cannot drift apart; checklist consumers render it with `renderSectionChecklist`.\n * The first three sections suffice for a small change, so they come first.\n */\nexport const CHANGE_ISSUE_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Background and goal',\n requirement: 'the problem being solved, for whom, and what outcome counts as success',\n },\n {\n heading: 'Behavior',\n requirement:\n 'every user- or caller-observable behavior, including inputs, outputs, error cases, edge cases, and interactions with existing behavior, stated precisely enough that two implementers would build the same thing',\n },\n {\n heading: 'Acceptance criteria',\n requirement:\n 'checkable conditions (Given/When/Then or an equivalent) that decide whether the implementation is done',\n },\n {\n heading: 'Scope and non-goals',\n requirement: 'what the change covers and what it deliberately leaves out, so an implementer knows where to stop',\n },\n {\n heading: 'Design constraints',\n requirement:\n 'the data, API, schema, UI, and configuration changes, naming, and the existing code or conventions the implementation must fit — as far as the writer intends to constrain them, with everything else explicitly left to the implementer',\n },\n {\n heading: 'Compatibility and migration',\n requirement: 'what existing data, users, callers, or configurations are affected and how the transition happens',\n },\n {\n heading: 'Verification',\n requirement: 'how the change is tested or demonstrated, including what needs no test and why',\n },\n {\n heading: 'Open questions',\n requirement: 'undecided points, each with its options; empty once the specification is implementable',\n },\n];\n\n/** Renders sections as markdown bullets (`- **Heading**: requirement`). */\nexport function renderSectionChecklist(sections: readonly TemplateSection[]): string {\n return sections.map((section) => `- **${section.heading}**: ${section.requirement}`).join('\\n');\n}\n\n/** Renders sections as markdown headings, each followed by its requirement as a placeholder comment. */\nexport function renderSectionTemplate(sections: readonly TemplateSection[]): string {\n return sections\n .map(\n (section) =>\n `## ${section.heading}\\n\\n<!-- ${section.requirement.charAt(0).toUpperCase()}${section.requirement.slice(1)}. -->`\n )\n .join('\\n\\n');\n}\n"],"mappings":"aAWA,MAAa,EAAoD,CAC/D,CACE,QAAS,MACT,YAAa,sGACf,EACA,CACE,QAAS,eACT,YACE,qnBACJ,EACA,CACE,QAAS,mBACT,YACE,4GACJ,EACA,CACE,QAAS,oBACT,YACE,yKACJ,EACA,CACE,QAAS,UACT,YAAa,+DACf,EACA,CACE,QAAS,QACT,YAAa,sGACf,CACF,EAiBa,EAAkC,y0DAMlC,EAA0B;qFAAmC,IAa7D,EAAiD,CAC5D,CAAE,QAAS,UAAW,YAAa,8CAA+C,EAClF,CAAE,QAAS,WAAY,YAAa,6CAA8C,EAClF,CAAE,QAAS,SAAU,YAAa,wCAAyC,EAC3E,CAAE,QAAS,WAAY,YAAa,uDAAwD,CAC9F,EAQa,EAAoD,CAC/D,CACE,QAAS,sBACT,YAAa,wEACf,EACA,CACE,QAAS,WACT,YACE,kNACJ,EACA,CACE,QAAS,sBACT,YACE,wGACJ,EACA,CACE,QAAS,sBACT,YAAa,mGACf,EACA,CACE,QAAS,qBACT,YACE,0OACJ,EACA,CACE,QAAS,8BACT,YAAa,mGACf,EACA,CACE,QAAS,eACT,YAAa,gFACf,EACA,CACE,QAAS,iBACT,YAAa,wFACf,CACF,EAGA,SAAgB,EAAuB,EAA8C,CACnF,OAAO,EAAS,IAAK,GAAY,OAAO,EAAQ,QAAQ,MAAM,EAAQ,aAAa,CAAC,CAAC,KAAK;CAAI,CAChG,CAGA,SAAgB,EAAsB,EAA8C,CAClF,OAAO,EACJ,IACE,GACC,MAAM,EAAQ,QAAQ,WAAW,EAAQ,YAAY,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,EAAQ,YAAY,MAAM,CAAC,EAAE,MAChH,CAAC,CACA,KAAK;;CAAM,CAChB"}
@@ -15,9 +15,9 @@ export declare const PULL_REQUEST_SECTIONS: readonly TemplateSection[];
15
15
  * bodies render this text instead of restating it, so the writers and the reviewers that read the
16
16
  * section as the boundary a fix must keep never disagree on what a line means.
17
17
  */
18
- export declare const PULL_REQUEST_REQUIREMENTS_RULES = "- Requirements section: one line per requirement, taken from the requester's instructions as they were given (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded \u2014 ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Record rule: an existing Requirements section is a record, not a description of the diff. Keep its `required` lines as they are, rewriting them only when the requester's instructions changed (then from the updated instructions, dropping a line only when the requester removed it; with no instructions available, keep them unchanged); add a `chosen` line for a new decision, and replace or remove one when the decision it records changed. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.";
18
+ export declare const PULL_REQUEST_REQUIREMENTS_RULES = "- Requirements section: the requirements in force now, one line per requirement, taken from the requester's instructions in the requester's terms (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision with the reason that decided it, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded \u2014 ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Current-state rule: an existing Requirements section records what the requester asked for and what was decided as it stands now; it is neither a description of the diff nor a log of how the request evolved. Keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of appending a line beside it; with no instructions available, keep the requester-derived lines unchanged. Never mark when a line was added (e.g., \"(added)\"), and add a `chosen` line for each new decision. When the current design cannot be understood without the change of direction, state it in one sentence in Notes. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.";
19
19
  /** The complete rules for writing a PR body: the template rules followed by the Requirements rules. */
20
- export declare const PULL_REQUEST_BODY_RULES = "- Base the PR body on `.github/pull_request_template.md` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.\n- Start the body with `Close #<n>` only when the PR resolves an existing issue.\n- Requirements section: one line per requirement, taken from the requester's instructions as they were given (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded \u2014 ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Record rule: an existing Requirements section is a record, not a description of the diff. Keep its `required` lines as they are, rewriting them only when the requester's instructions changed (then from the updated instructions, dropping a line only when the requester removed it; with no instructions available, keep them unchanged); add a `chosen` line for a new decision, and replace or remove one when the decision it records changed. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.";
20
+ export declare const PULL_REQUEST_BODY_RULES = "- Base the PR body on `.github/pull_request_template.md` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.\n- Start the body with `Close #<n>` only when the PR resolves an existing issue.\n- Requirements section: the requirements in force now, one line per requirement, taken from the requester's instructions in the requester's terms (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision with the reason that decided it, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded \u2014 ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Current-state rule: an existing Requirements section records what the requester asked for and what was decided as it stands now; it is neither a description of the diff nor a log of how the request evolved. Keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of appending a line beside it; with no instructions available, keep the requester-derived lines unchanged. Never mark when a line was added (e.g., \"(added)\"), and add a `chosen` line for each new decision. When the current design cannot be understood without the change of direction, state it in one sentence in Notes. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.";
21
21
  /**
22
22
  * How a tool that creates an issue derives it from the repository's issue templates, as markdown
23
23
  * bullets for an agent's instructions; shared by the same writers as `PULL_REQUEST_BODY_RULES`.
@@ -1,4 +1,4 @@
1
- const e=[{heading:`Why`,requirement:`the problem, with the numbers or observations behind it, and why this approach over the alternatives`},{heading:`Requirements`,requirement:"the requirements the change must satisfy and the guarantees it must keep, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision, which a simpler design may replace); copy the requester's instructions here as given, whether they came from an issue or a conversation, and keep the list when the body is later rewritten unless the requester's instructions changed"},{heading:`Customer Summary`,requirement:`behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation`},{heading:`Technical Summary`,requirement:`decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven`},{heading:`Testing`,requirement:`commands run, tests added, and what was NOT exercised and why`},{heading:`Notes`,requirement:`known limitations, compatibility and migration, follow-up work; delete this section if there is none`}],t="- Requirements section: one line per requirement, taken from the requester's instructions as they were given (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded — ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Record rule: an existing Requirements section is a record, not a description of the diff. Keep its `required` lines as they are, rewriting them only when the requester's instructions changed (then from the updated instructions, dropping a line only when the requester removed it; with no instructions available, keep them unchanged); add a `chosen` line for a new decision, and replace or remove one when the decision it records changed. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.",n=`- Base the PR body on \`.github/pull_request_template.md\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.
1
+ const e=[{heading:`Why`,requirement:`the problem, with the numbers or observations behind it, and why this approach over the alternatives`},{heading:`Requirements`,requirement:"the requirements the change must satisfy and the guarantees it must keep as they stand now, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision with the reason that decided it, which a simpler design may replace); state the requester's instructions in the requester's terms, whether they came from an issue or a conversation, and keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of adding one beside it"},{heading:`Customer Summary`,requirement:`behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation`},{heading:`Technical Summary`,requirement:`decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven`},{heading:`Testing`,requirement:`commands run, tests added, and what was NOT exercised and why`},{heading:`Notes`,requirement:`known limitations, compatibility and migration, follow-up work; delete this section if there is none`}],t="- Requirements section: the requirements in force now, one line per requirement, taken from the requester's instructions in the requester's terms (the issue, the conversation that asked for the change), each marked `required` (asked for, or an existing contract callers depend on) or `chosen` (your own decision with the reason that decided it, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write `required: not recorded — ask the requester` as the only request-derived line (a `required` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Current-state rule: an existing Requirements section records what the requester asked for and what was decided as it stands now; it is neither a description of the diff nor a log of how the request evolved. Keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of appending a line beside it; with no instructions available, keep the requester-derived lines unchanged. Never mark when a line was added (e.g., \"(added)\"), and add a `chosen` line for each new decision. When the current design cannot be understood without the change of direction, state it in one sentence in Notes. A section that merely describes the implementation, or holds only the template's placeholder or a `required: not recorded` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a `required` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.",n=`- Base the PR body on \`.github/pull_request_template.md\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.
2
2
  - Start the body with \`Close #<n>\` only when the PR resolves an existing issue.\n${t}`,r="- Follow the closest template under `.github/ISSUE_TEMPLATE/`: `bug.md` for wrong behavior, `change.md` for anything to build or alter; a question or note fitting neither, or a repository without templates, needs no template.\n- Title: a Conventional Commits prefix for the type that fits the change (`feat:`, `fix:`, `refactor:`, `docs:`, `chore:`, ...); when it differs from the template's `title` prefix, replace the template's type label (`t: ...`) with the one matching the type.\n- The YAML front matter between the `---` lines is metadata, not body text: pass its `labels` via `--label` and submit only the content below the closing `---` as the body.",i=[{heading:`Problem`,requirement:`what happens, and what should happen instead`},{heading:`Evidence`,requirement:`reproduction steps, logs, run IDs, or links`},{heading:`Impact`,requirement:`who or what is affected, and how badly`},{heading:`Proposal`,requirement:`the fix you have in mind, and the root cause if known`}],a=[{heading:`Background and goal`,requirement:`the problem being solved, for whom, and what outcome counts as success`},{heading:`Behavior`,requirement:`every user- or caller-observable behavior, including inputs, outputs, error cases, edge cases, and interactions with existing behavior, stated precisely enough that two implementers would build the same thing`},{heading:`Acceptance criteria`,requirement:`checkable conditions (Given/When/Then or an equivalent) that decide whether the implementation is done`},{heading:`Scope and non-goals`,requirement:`what the change covers and what it deliberately leaves out, so an implementer knows where to stop`},{heading:`Design constraints`,requirement:`the data, API, schema, UI, and configuration changes, naming, and the existing code or conventions the implementation must fit — as far as the writer intends to constrain them, with everything else explicitly left to the implementer`},{heading:`Compatibility and migration`,requirement:`what existing data, users, callers, or configurations are affected and how the transition happens`},{heading:`Verification`,requirement:`how the change is tested or demonstrated, including what needs no test and why`},{heading:`Open questions`,requirement:`undecided points, each with its options; empty once the specification is implementable`}];function o(e){return e.map(e=>`- **${e.heading}**: ${e.requirement}`).join(`
3
3
  `)}function s(e){return e.map(e=>`## ${e.heading}\n\n<!-- ${e.requirement.charAt(0).toUpperCase()}${e.requirement.slice(1)}. -->`).join(`
4
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"githubTemplates.js","names":[],"sources":["../src/githubTemplates.ts"],"sourcesContent":["/**\n * A section of a PR or issue body: its heading and what the section must state. `requirement`\n * starts lowercase and ends without punctuation, so that it reads both as a placeholder sentence\n * (capitalized, with a period appended) and as a checklist clause after the heading.\n */\nexport interface TemplateSection {\n readonly heading: string;\n readonly requirement: string;\n}\n\n/** Sections of a pull request body, in the order they appear in the PR template. */\nexport const PULL_REQUEST_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Why',\n requirement: 'the problem, with the numbers or observations behind it, and why this approach over the alternatives',\n },\n {\n heading: 'Requirements',\n requirement:\n \"the requirements the change must satisfy and the guarantees it must keep, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision, which a simpler design may replace); copy the requester's instructions here as given, whether they came from an issue or a conversation, and keep the list when the body is later rewritten unless the requester's instructions changed\",\n },\n {\n heading: 'Customer Summary',\n requirement:\n 'behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation',\n },\n {\n heading: 'Technical Summary',\n requirement:\n 'decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven',\n },\n {\n heading: 'Testing',\n requirement: 'commands run, tests added, and what was NOT exercised and why',\n },\n {\n heading: 'Notes',\n requirement: 'known limitations, compatibility and migration, follow-up work; delete this section if there is none',\n },\n];\n\n/**\n * How a tool that writes or rewrites a PR body derives it from the repository's PR template, as\n * markdown bullets for an agent's instructions. Stated once here and rendered by every writer (the\n * generated agent instructions, the PR-drafting skills) so the writers cannot drift apart; the\n * template-less branch lets the same text serve repositories outside the organization.\n */\nconst PULL_REQUEST_TEMPLATE_RULES = `- Base the PR body on \\`.github/pull_request_template.md\\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.\n- Start the body with \\`Close #<n>\\` only when the PR resolves an existing issue.`;\n\n/**\n * How a tool that writes or rewrites a PR body fills the Requirements section of\n * `PULL_REQUEST_SECTIONS`, as markdown bullets for an agent's instructions. Skills that draft PR\n * bodies render this text instead of restating it, so the writers and the reviewers that read the\n * section as the boundary a fix must keep never disagree on what a line means.\n */\nexport const PULL_REQUEST_REQUIREMENTS_RULES = `- Requirements section: one line per requirement, taken from the requester's instructions as they were given (the issue, the conversation that asked for the change), each marked \\`required\\` (asked for, or an existing contract callers depend on) or \\`chosen\\` (your own decision, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write \\`required: not recorded — ask the requester\\` as the only request-derived line (a \\`required\\` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Record rule: an existing Requirements section is a record, not a description of the diff. Keep its \\`required\\` lines as they are, rewriting them only when the requester's instructions changed (then from the updated instructions, dropping a line only when the requester removed it; with no instructions available, keep them unchanged); add a \\`chosen\\` line for a new decision, and replace or remove one when the decision it records changed. A section that merely describes the implementation, or holds only the template's placeholder or a \\`required: not recorded\\` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a \\`required\\` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.`;\n\n/** The complete rules for writing a PR body: the template rules followed by the Requirements rules. */\nexport const PULL_REQUEST_BODY_RULES = `${PULL_REQUEST_TEMPLATE_RULES}\\n${PULL_REQUEST_REQUIREMENTS_RULES}`;\n\n/**\n * How a tool that creates an issue derives it from the repository's issue templates, as markdown\n * bullets for an agent's instructions; shared by the same writers as `PULL_REQUEST_BODY_RULES`.\n * Guidance the templates state in their own placeholder comments (which sections to keep, deleting\n * the comments) is deliberately not repeated here, since the writer reads the template anyway.\n */\nexport const ISSUE_TEMPLATE_RULES = `- Follow the closest template under \\`.github/ISSUE_TEMPLATE/\\`: \\`bug.md\\` for wrong behavior, \\`change.md\\` for anything to build or alter; a question or note fitting neither, or a repository without templates, needs no template.\n- Title: a Conventional Commits prefix for the type that fits the change (\\`feat:\\`, \\`fix:\\`, \\`refactor:\\`, \\`docs:\\`, \\`chore:\\`, ...); when it differs from the template's \\`title\\` prefix, replace the template's type label (\\`t: ...\\`) with the one matching the type.\n- The YAML front matter between the \\`---\\` lines is metadata, not body text: pass its \\`labels\\` via \\`--label\\` and submit only the content below the closing \\`---\\` as the body.`;\n\n/** Sections of a bug report, in the order they appear in the issue template. */\nexport const BUG_ISSUE_SECTIONS: readonly TemplateSection[] = [\n { heading: 'Problem', requirement: 'what happens, and what should happen instead' },\n { heading: 'Evidence', requirement: 'reproduction steps, logs, run IDs, or links' },\n { heading: 'Impact', requirement: 'who or what is affected, and how badly' },\n { heading: 'Proposal', requirement: 'the fix you have in mind, and the root cause if known' },\n];\n\n/**\n * Sections a change specification must settle before a third party can implement it, defined\n * once so that the issue template and any tool that drafts or reviews specifications against\n * these sections cannot drift apart; checklist consumers render it with `renderSectionChecklist`.\n * The first three sections suffice for a small change, so they come first.\n */\nexport const CHANGE_ISSUE_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Background and goal',\n requirement: 'the problem being solved, for whom, and what outcome counts as success',\n },\n {\n heading: 'Behavior',\n requirement:\n 'every user- or caller-observable behavior, including inputs, outputs, error cases, edge cases, and interactions with existing behavior, stated precisely enough that two implementers would build the same thing',\n },\n {\n heading: 'Acceptance criteria',\n requirement:\n 'checkable conditions (Given/When/Then or an equivalent) that decide whether the implementation is done',\n },\n {\n heading: 'Scope and non-goals',\n requirement: 'what the change covers and what it deliberately leaves out, so an implementer knows where to stop',\n },\n {\n heading: 'Design constraints',\n requirement:\n 'the data, API, schema, UI, and configuration changes, naming, and the existing code or conventions the implementation must fit — as far as the writer intends to constrain them, with everything else explicitly left to the implementer',\n },\n {\n heading: 'Compatibility and migration',\n requirement: 'what existing data, users, callers, or configurations are affected and how the transition happens',\n },\n {\n heading: 'Verification',\n requirement: 'how the change is tested or demonstrated, including what needs no test and why',\n },\n {\n heading: 'Open questions',\n requirement: 'undecided points, each with its options; empty once the specification is implementable',\n },\n];\n\n/** Renders sections as markdown bullets (`- **Heading**: requirement`). */\nexport function renderSectionChecklist(sections: readonly TemplateSection[]): string {\n return sections.map((section) => `- **${section.heading}**: ${section.requirement}`).join('\\n');\n}\n\n/** Renders sections as markdown headings, each followed by its requirement as a placeholder comment. */\nexport function renderSectionTemplate(sections: readonly TemplateSection[]): string {\n return sections\n .map(\n (section) =>\n `## ${section.heading}\\n\\n<!-- ${section.requirement.charAt(0).toUpperCase()}${section.requirement.slice(1)}. -->`\n )\n .join('\\n\\n');\n}\n"],"mappings":"AAWA,MAAa,EAAoD,CAC/D,CACE,QAAS,MACT,YAAa,sGACf,EACA,CACE,QAAS,eACT,YACE,6cACJ,EACA,CACE,QAAS,mBACT,YACE,4GACJ,EACA,CACE,QAAS,oBACT,YACE,yKACJ,EACA,CACE,QAAS,UACT,YAAa,+DACf,EACA,CACE,QAAS,QACT,YAAa,sGACf,CACF,EAiBa,EAAkC,6/CAMlC,EAA0B;qFAAmC,IAQ7D,EAAuB,qpBAKvB,EAAiD,CAC5D,CAAE,QAAS,UAAW,YAAa,8CAA+C,EAClF,CAAE,QAAS,WAAY,YAAa,6CAA8C,EAClF,CAAE,QAAS,SAAU,YAAa,wCAAyC,EAC3E,CAAE,QAAS,WAAY,YAAa,uDAAwD,CAC9F,EAQa,EAAoD,CAC/D,CACE,QAAS,sBACT,YAAa,wEACf,EACA,CACE,QAAS,WACT,YACE,kNACJ,EACA,CACE,QAAS,sBACT,YACE,wGACJ,EACA,CACE,QAAS,sBACT,YAAa,mGACf,EACA,CACE,QAAS,qBACT,YACE,0OACJ,EACA,CACE,QAAS,8BACT,YAAa,mGACf,EACA,CACE,QAAS,eACT,YAAa,gFACf,EACA,CACE,QAAS,iBACT,YAAa,wFACf,CACF,EAGA,SAAgB,EAAuB,EAA8C,CACnF,OAAO,EAAS,IAAK,GAAY,OAAO,EAAQ,QAAQ,MAAM,EAAQ,aAAa,CAAC,CAAC,KAAK;CAAI,CAChG,CAGA,SAAgB,EAAsB,EAA8C,CAClF,OAAO,EACJ,IACE,GACC,MAAM,EAAQ,QAAQ,WAAW,EAAQ,YAAY,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,EAAQ,YAAY,MAAM,CAAC,EAAE,MAChH,CAAC,CACA,KAAK;;CAAM,CAChB"}
1
+ {"version":3,"file":"githubTemplates.js","names":[],"sources":["../src/githubTemplates.ts"],"sourcesContent":["/**\n * A section of a PR or issue body: its heading and what the section must state. `requirement`\n * starts lowercase and ends without punctuation, so that it reads both as a placeholder sentence\n * (capitalized, with a period appended) and as a checklist clause after the heading.\n */\nexport interface TemplateSection {\n readonly heading: string;\n readonly requirement: string;\n}\n\n/** Sections of a pull request body, in the order they appear in the PR template. */\nexport const PULL_REQUEST_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Why',\n requirement: 'the problem, with the numbers or observations behind it, and why this approach over the alternatives',\n },\n {\n heading: 'Requirements',\n requirement:\n \"the requirements the change must satisfy and the guarantees it must keep as they stand now, one per line, each marked `required` (asked for by the requester, or an existing contract callers depend on) or `chosen` (the implementer's own decision with the reason that decided it, which a simpler design may replace); state the requester's instructions in the requester's terms, whether they came from an issue or a conversation, and keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of adding one beside it\",\n },\n {\n heading: 'Customer Summary',\n requirement:\n 'behavior, workflow, or user-visible changes, written for readers who know nothing about the implementation',\n },\n {\n heading: 'Technical Summary',\n requirement:\n 'decisions and their reasons, data flow, where to look (the files that matter most), and what to check hardest: the parts whose correctness is argued rather than proven',\n },\n {\n heading: 'Testing',\n requirement: 'commands run, tests added, and what was NOT exercised and why',\n },\n {\n heading: 'Notes',\n requirement: 'known limitations, compatibility and migration, follow-up work; delete this section if there is none',\n },\n];\n\n/**\n * How a tool that writes or rewrites a PR body derives it from the repository's PR template, as\n * markdown bullets for an agent's instructions. Stated once here and rendered by every writer (the\n * generated agent instructions, the PR-drafting skills) so the writers cannot drift apart; the\n * template-less branch lets the same text serve repositories outside the organization.\n */\nconst PULL_REQUEST_TEMPLATE_RULES = `- Base the PR body on \\`.github/pull_request_template.md\\` when creating or updating a PR, even when a skill or workflow supplies its own skeleton: keep the template's headings in order, fill each section with what its placeholder comment asks for at a length fitting the change (a sentence for a small change, numbered subsections for a large one), and delete the placeholder comments and an empty Notes section. Without a template, use no fixed headings: state the scope, the motivation, and the verification concisely.\n- Start the body with \\`Close #<n>\\` only when the PR resolves an existing issue.`;\n\n/**\n * How a tool that writes or rewrites a PR body fills the Requirements section of\n * `PULL_REQUEST_SECTIONS`, as markdown bullets for an agent's instructions. Skills that draft PR\n * bodies render this text instead of restating it, so the writers and the reviewers that read the\n * section as the boundary a fix must keep never disagree on what a line means.\n */\nexport const PULL_REQUEST_REQUIREMENTS_RULES = `- Requirements section: the requirements in force now, one line per requirement, taken from the requester's instructions in the requester's terms (the issue, the conversation that asked for the change), each marked \\`required\\` (asked for, or an existing contract callers depend on) or \\`chosen\\` (your own decision with the reason that decided it, which a simpler design may replace). Never infer a requirement from the diff: when no issue, PR message, or conversation states the request, write \\`required: not recorded — ask the requester\\` as the only request-derived line (a \\`required\\` line for an existing contract callers depend on may still be listed) and say so in Notes.\n- Current-state rule: an existing Requirements section records what the requester asked for and what was decided as it stands now; it is neither a description of the diff nor a log of how the request evolved. Keep each line as it is until the requester overrides or withdraws the instruction behind it or the decision behind it changes, and then rewrite or remove that line instead of appending a line beside it; with no instructions available, keep the requester-derived lines unchanged. Never mark when a line was added (e.g., \"(added)\"), and add a \\`chosen\\` line for each new decision. When the current design cannot be understood without the change of direction, state it in one sentence in Notes. A section that merely describes the implementation, or holds only the template's placeholder or a \\`required: not recorded\\` line, is not a record: write it afresh by the rule above.\n- Place the section where the template puts it; when the template has no such heading, right after the issue-closing line, or at the top of the body when there is none.\n- Never drop or weaken a \\`required\\` line to fit what was implemented: when one cannot hold in the diff, keep it and say so in Notes.`;\n\n/** The complete rules for writing a PR body: the template rules followed by the Requirements rules. */\nexport const PULL_REQUEST_BODY_RULES = `${PULL_REQUEST_TEMPLATE_RULES}\\n${PULL_REQUEST_REQUIREMENTS_RULES}`;\n\n/**\n * How a tool that creates an issue derives it from the repository's issue templates, as markdown\n * bullets for an agent's instructions; shared by the same writers as `PULL_REQUEST_BODY_RULES`.\n * Guidance the templates state in their own placeholder comments (which sections to keep, deleting\n * the comments) is deliberately not repeated here, since the writer reads the template anyway.\n */\nexport const ISSUE_TEMPLATE_RULES = `- Follow the closest template under \\`.github/ISSUE_TEMPLATE/\\`: \\`bug.md\\` for wrong behavior, \\`change.md\\` for anything to build or alter; a question or note fitting neither, or a repository without templates, needs no template.\n- Title: a Conventional Commits prefix for the type that fits the change (\\`feat:\\`, \\`fix:\\`, \\`refactor:\\`, \\`docs:\\`, \\`chore:\\`, ...); when it differs from the template's \\`title\\` prefix, replace the template's type label (\\`t: ...\\`) with the one matching the type.\n- The YAML front matter between the \\`---\\` lines is metadata, not body text: pass its \\`labels\\` via \\`--label\\` and submit only the content below the closing \\`---\\` as the body.`;\n\n/** Sections of a bug report, in the order they appear in the issue template. */\nexport const BUG_ISSUE_SECTIONS: readonly TemplateSection[] = [\n { heading: 'Problem', requirement: 'what happens, and what should happen instead' },\n { heading: 'Evidence', requirement: 'reproduction steps, logs, run IDs, or links' },\n { heading: 'Impact', requirement: 'who or what is affected, and how badly' },\n { heading: 'Proposal', requirement: 'the fix you have in mind, and the root cause if known' },\n];\n\n/**\n * Sections a change specification must settle before a third party can implement it, defined\n * once so that the issue template and any tool that drafts or reviews specifications against\n * these sections cannot drift apart; checklist consumers render it with `renderSectionChecklist`.\n * The first three sections suffice for a small change, so they come first.\n */\nexport const CHANGE_ISSUE_SECTIONS: readonly TemplateSection[] = [\n {\n heading: 'Background and goal',\n requirement: 'the problem being solved, for whom, and what outcome counts as success',\n },\n {\n heading: 'Behavior',\n requirement:\n 'every user- or caller-observable behavior, including inputs, outputs, error cases, edge cases, and interactions with existing behavior, stated precisely enough that two implementers would build the same thing',\n },\n {\n heading: 'Acceptance criteria',\n requirement:\n 'checkable conditions (Given/When/Then or an equivalent) that decide whether the implementation is done',\n },\n {\n heading: 'Scope and non-goals',\n requirement: 'what the change covers and what it deliberately leaves out, so an implementer knows where to stop',\n },\n {\n heading: 'Design constraints',\n requirement:\n 'the data, API, schema, UI, and configuration changes, naming, and the existing code or conventions the implementation must fit — as far as the writer intends to constrain them, with everything else explicitly left to the implementer',\n },\n {\n heading: 'Compatibility and migration',\n requirement: 'what existing data, users, callers, or configurations are affected and how the transition happens',\n },\n {\n heading: 'Verification',\n requirement: 'how the change is tested or demonstrated, including what needs no test and why',\n },\n {\n heading: 'Open questions',\n requirement: 'undecided points, each with its options; empty once the specification is implementable',\n },\n];\n\n/** Renders sections as markdown bullets (`- **Heading**: requirement`). */\nexport function renderSectionChecklist(sections: readonly TemplateSection[]): string {\n return sections.map((section) => `- **${section.heading}**: ${section.requirement}`).join('\\n');\n}\n\n/** Renders sections as markdown headings, each followed by its requirement as a placeholder comment. */\nexport function renderSectionTemplate(sections: readonly TemplateSection[]): string {\n return sections\n .map(\n (section) =>\n `## ${section.heading}\\n\\n<!-- ${section.requirement.charAt(0).toUpperCase()}${section.requirement.slice(1)}. -->`\n )\n .join('\\n\\n');\n}\n"],"mappings":"AAWA,MAAa,EAAoD,CAC/D,CACE,QAAS,MACT,YAAa,sGACf,EACA,CACE,QAAS,eACT,YACE,qnBACJ,EACA,CACE,QAAS,mBACT,YACE,4GACJ,EACA,CACE,QAAS,oBACT,YACE,yKACJ,EACA,CACE,QAAS,UACT,YAAa,+DACf,EACA,CACE,QAAS,QACT,YAAa,sGACf,CACF,EAiBa,EAAkC,y0DAMlC,EAA0B;qFAAmC,IAQ7D,EAAuB,qpBAKvB,EAAiD,CAC5D,CAAE,QAAS,UAAW,YAAa,8CAA+C,EAClF,CAAE,QAAS,WAAY,YAAa,6CAA8C,EAClF,CAAE,QAAS,SAAU,YAAa,wCAAyC,EAC3E,CAAE,QAAS,WAAY,YAAa,uDAAwD,CAC9F,EAQa,EAAoD,CAC/D,CACE,QAAS,sBACT,YAAa,wEACf,EACA,CACE,QAAS,WACT,YACE,kNACJ,EACA,CACE,QAAS,sBACT,YACE,wGACJ,EACA,CACE,QAAS,sBACT,YAAa,mGACf,EACA,CACE,QAAS,qBACT,YACE,0OACJ,EACA,CACE,QAAS,8BACT,YAAa,mGACf,EACA,CACE,QAAS,eACT,YAAa,gFACf,EACA,CACE,QAAS,iBACT,YAAa,wFACf,CACF,EAGA,SAAgB,EAAuB,EAA8C,CACnF,OAAO,EAAS,IAAK,GAAY,OAAO,EAAQ,QAAQ,MAAM,EAAQ,aAAa,CAAC,CAAC,KAAK;CAAI,CAChG,CAGA,SAAgB,EAAsB,EAA8C,CAClF,OAAO,EACJ,IACE,GACC,MAAM,EAAQ,QAAQ,WAAW,EAAQ,YAAY,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,EAAQ,YAAY,MAAM,CAAC,EAAE,MAChH,CAAC,CACA,KAAK;;CAAM,CAChB"}
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./appEnv.cjs"),t=require("./assert.cjs"),n=require("./githubTemplates.cjs"),r=require("./sleep.cjs"),i=require("./error.cjs"),a=require("./humanize.cjs"),o=require("./mail.cjs"),s=require("./parseCommandLineArgs.cjs"),c=require("./text.cjs"),l=require("./prompt.cjs"),u=require("./shuffle.cjs"),d=require("./sqlite.cjs"),f=require("./testingRules.cjs"),p=require("./zenkaku.cjs");exports.BUG_ISSUE_SECTIONS=n.BUG_ISSUE_SECTIONS,exports.CHANGE_ISSUE_SECTIONS=n.CHANGE_ISSUE_SECTIONS,exports.ISSUE_TEMPLATE_RULES=n.ISSUE_TEMPLATE_RULES,exports.PULL_REQUEST_BODY_RULES=n.PULL_REQUEST_BODY_RULES,exports.PULL_REQUEST_REQUIREMENTS_RULES=n.PULL_REQUEST_REQUIREMENTS_RULES,exports.PULL_REQUEST_SECTIONS=n.PULL_REQUEST_SECTIONS,exports.TEST_WRITING_RULES=f.TEST_WRITING_RULES,exports.ensureTruthy=t.ensureTruthy,exports.errorify=i.errorify,exports.escapePromptTag=l.escapePromptTag,exports.escapeRegExp=c.escapeRegExp,exports.formatPrompt=l.formatPrompt,exports.getAppEnv=e.getAppEnv,exports.getConnectionLevelSqlitePragmas=d.getConnectionLevelSqlitePragmas,exports.getPersistentSqlitePragmas=d.getPersistentSqlitePragmas,exports.humanizeNumber=a.humanizeNumber,exports.ignoreEnoent=i.ignoreEnoent,exports.ignoreEnoentAsync=i.ignoreEnoentAsync,exports.ignoreError=i.ignoreError,exports.ignoreErrorAsync=i.ignoreErrorAsync,exports.mailTemplates=o.mailTemplates,exports.parseCommandLineArgs=s.parseCommandLineArgs,exports.quoteForShell=c.quoteForShell,exports.renderSectionChecklist=n.renderSectionChecklist,exports.renderSectionTemplate=n.renderSectionTemplate,exports.serializeForPrompt=l.serializeForPrompt,exports.serializeForPromptInTag=l.serializeForPromptInTag,exports.shuffle=u.shuffle,exports.sleep=r.sleep,exports.toCodeBlock=c.toCodeBlock,exports.toTildeCodeBlock=c.toTildeCodeBlock,exports.truncateForPrompt=l.truncateForPrompt,exports.withRetry=i.withRetry,exports.zenkakuAlphanumericalsToHankaku=p.zenkakuAlphanumericalsToHankaku;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./appEnv.cjs"),t=require("./assert.cjs"),n=require("./githubTemplates.cjs"),r=require("./sleep.cjs"),i=require("./error.cjs"),a=require("./humanize.cjs"),o=require("./mail.cjs"),s=require("./markdown.cjs"),c=require("./parseCommandLineArgs.cjs"),l=require("./text.cjs"),u=require("./prompt.cjs"),d=require("./promptFormatters.cjs"),f=require("./shuffle.cjs"),p=require("./sqlite.cjs"),m=require("./testingRules.cjs"),h=require("./zenkaku.cjs");exports.BUG_ISSUE_SECTIONS=n.BUG_ISSUE_SECTIONS,exports.CHANGE_ISSUE_SECTIONS=n.CHANGE_ISSUE_SECTIONS,exports.ISSUE_TEMPLATE_RULES=n.ISSUE_TEMPLATE_RULES,exports.PULL_REQUEST_BODY_RULES=n.PULL_REQUEST_BODY_RULES,exports.PULL_REQUEST_REQUIREMENTS_RULES=n.PULL_REQUEST_REQUIREMENTS_RULES,exports.PULL_REQUEST_SECTIONS=n.PULL_REQUEST_SECTIONS,exports.TEST_WRITING_RULES=m.TEST_WRITING_RULES,exports.ensureTruthy=t.ensureTruthy,exports.errorify=i.errorify,exports.escapePromptTag=u.escapePromptTag,exports.escapeRegExp=l.escapeRegExp,exports.extractCodeBlocks=s.extractCodeBlocks,exports.extractIfSingleOutermostCodeBlock=s.extractIfSingleOutermostCodeBlock,exports.extractSections=s.extractSections,exports.formatFilesForPrompt=d.formatFilesForPrompt,exports.formatMessagesForPrompt=d.formatMessagesForPrompt,exports.formatPrompt=u.formatPrompt,exports.getAppEnv=e.getAppEnv,exports.getConnectionLevelSqlitePragmas=p.getConnectionLevelSqlitePragmas,exports.getPersistentSqlitePragmas=p.getPersistentSqlitePragmas,exports.humanizeNumber=a.humanizeNumber,exports.ignoreEnoent=i.ignoreEnoent,exports.ignoreEnoentAsync=i.ignoreEnoentAsync,exports.ignoreError=i.ignoreError,exports.ignoreErrorAsync=i.ignoreErrorAsync,exports.mailTemplates=o.mailTemplates,exports.parseCommandLineArgs=c.parseCommandLineArgs,exports.parseMarkdownSections=s.parseMarkdownSections,exports.quoteForShell=l.quoteForShell,exports.renderSectionChecklist=n.renderSectionChecklist,exports.renderSectionTemplate=n.renderSectionTemplate,exports.serializeForPrompt=u.serializeForPrompt,exports.serializeForPromptInTag=u.serializeForPromptInTag,exports.shuffle=f.shuffle,exports.sleep=r.sleep,exports.toCodeBlock=l.toCodeBlock,exports.toTildeCodeBlock=l.toTildeCodeBlock,exports.truncateForPrompt=u.truncateForPrompt,exports.withRetry=i.withRetry,exports.zenkakuAlphanumericalsToHankaku=h.zenkakuAlphanumericalsToHankaku;
package/dist/index.d.ts CHANGED
@@ -4,8 +4,10 @@ export { BUG_ISSUE_SECTIONS, CHANGE_ISSUE_SECTIONS, ISSUE_TEMPLATE_RULES, PULL_R
4
4
  export { errorify, ignoreError, ignoreEnoent, ignoreErrorAsync, ignoreEnoentAsync, withRetry } from './error.js';
5
5
  export { humanizeNumber } from './humanize.js';
6
6
  export { mailTemplates } from './mail.js';
7
+ export { extractCodeBlocks, extractIfSingleOutermostCodeBlock, extractSections, parseMarkdownSections, } from './markdown.js';
7
8
  export { parseCommandLineArgs } from './parseCommandLineArgs.js';
8
9
  export { escapePromptTag, formatPrompt, serializeForPrompt, serializeForPromptInTag, truncateForPrompt, } from './prompt.js';
10
+ export { formatFilesForPrompt, formatMessagesForPrompt } from './promptFormatters.js';
9
11
  export { shuffle } from './shuffle.js';
10
12
  export { sleep } from './sleep.js';
11
13
  export { getConnectionLevelSqlitePragmas, getPersistentSqlitePragmas } from './sqlite.js';
@@ -14,4 +16,5 @@ export { TEST_WRITING_RULES } from './testingRules.js';
14
16
  export { zenkakuAlphanumericalsToHankaku } from './zenkaku.js';
15
17
  export type { AppEnv } from './appEnv.js';
16
18
  export type { RetryOptions } from './error.js';
19
+ export type { CodeBlock, MarkdownSection } from './markdown.js';
17
20
  export type { TemplateSection } from './githubTemplates.js';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{getAppEnv as e}from"./appEnv.js";import{ensureTruthy as t}from"./assert.js";import{BUG_ISSUE_SECTIONS as n,CHANGE_ISSUE_SECTIONS as r,ISSUE_TEMPLATE_RULES as i,PULL_REQUEST_BODY_RULES as a,PULL_REQUEST_REQUIREMENTS_RULES as o,PULL_REQUEST_SECTIONS as s,renderSectionChecklist as c,renderSectionTemplate as l}from"./githubTemplates.js";import{sleep as u}from"./sleep.js";import{errorify as d,ignoreEnoent as f,ignoreEnoentAsync as p,ignoreError as m,ignoreErrorAsync as h,withRetry as g}from"./error.js";import{humanizeNumber as _}from"./humanize.js";import{mailTemplates as v}from"./mail.js";import{parseCommandLineArgs as y}from"./parseCommandLineArgs.js";import{escapeRegExp as b,quoteForShell as x,toCodeBlock as S,toTildeCodeBlock as C}from"./text.js";import{escapePromptTag as w,formatPrompt as T,serializeForPrompt as E,serializeForPromptInTag as D,truncateForPrompt as O}from"./prompt.js";import{shuffle as k}from"./shuffle.js";import{getConnectionLevelSqlitePragmas as A,getPersistentSqlitePragmas as j}from"./sqlite.js";import{TEST_WRITING_RULES as M}from"./testingRules.js";import{zenkakuAlphanumericalsToHankaku as N}from"./zenkaku.js";export{n as BUG_ISSUE_SECTIONS,r as CHANGE_ISSUE_SECTIONS,i as ISSUE_TEMPLATE_RULES,a as PULL_REQUEST_BODY_RULES,o as PULL_REQUEST_REQUIREMENTS_RULES,s as PULL_REQUEST_SECTIONS,M as TEST_WRITING_RULES,t as ensureTruthy,d as errorify,w as escapePromptTag,b as escapeRegExp,T as formatPrompt,e as getAppEnv,A as getConnectionLevelSqlitePragmas,j as getPersistentSqlitePragmas,_ as humanizeNumber,f as ignoreEnoent,p as ignoreEnoentAsync,m as ignoreError,h as ignoreErrorAsync,v as mailTemplates,y as parseCommandLineArgs,x as quoteForShell,c as renderSectionChecklist,l as renderSectionTemplate,E as serializeForPrompt,D as serializeForPromptInTag,k as shuffle,u as sleep,S as toCodeBlock,C as toTildeCodeBlock,O as truncateForPrompt,g as withRetry,N as zenkakuAlphanumericalsToHankaku};
1
+ import{getAppEnv as e}from"./appEnv.js";import{ensureTruthy as t}from"./assert.js";import{BUG_ISSUE_SECTIONS as n,CHANGE_ISSUE_SECTIONS as r,ISSUE_TEMPLATE_RULES as i,PULL_REQUEST_BODY_RULES as a,PULL_REQUEST_REQUIREMENTS_RULES as o,PULL_REQUEST_SECTIONS as s,renderSectionChecklist as c,renderSectionTemplate as l}from"./githubTemplates.js";import{sleep as u}from"./sleep.js";import{errorify as d,ignoreEnoent as f,ignoreEnoentAsync as p,ignoreError as m,ignoreErrorAsync as h,withRetry as g}from"./error.js";import{humanizeNumber as _}from"./humanize.js";import{mailTemplates as v}from"./mail.js";import{extractCodeBlocks as y,extractIfSingleOutermostCodeBlock as b,extractSections as x,parseMarkdownSections as S}from"./markdown.js";import{parseCommandLineArgs as C}from"./parseCommandLineArgs.js";import{escapeRegExp as w,quoteForShell as T,toCodeBlock as E,toTildeCodeBlock as D}from"./text.js";import{escapePromptTag as O,formatPrompt as k,serializeForPrompt as A,serializeForPromptInTag as j,truncateForPrompt as M}from"./prompt.js";import{formatFilesForPrompt as N,formatMessagesForPrompt as P}from"./promptFormatters.js";import{shuffle as F}from"./shuffle.js";import{getConnectionLevelSqlitePragmas as I,getPersistentSqlitePragmas as L}from"./sqlite.js";import{TEST_WRITING_RULES as R}from"./testingRules.js";import{zenkakuAlphanumericalsToHankaku as z}from"./zenkaku.js";export{n as BUG_ISSUE_SECTIONS,r as CHANGE_ISSUE_SECTIONS,i as ISSUE_TEMPLATE_RULES,a as PULL_REQUEST_BODY_RULES,o as PULL_REQUEST_REQUIREMENTS_RULES,s as PULL_REQUEST_SECTIONS,R as TEST_WRITING_RULES,t as ensureTruthy,d as errorify,O as escapePromptTag,w as escapeRegExp,y as extractCodeBlocks,b as extractIfSingleOutermostCodeBlock,x as extractSections,N as formatFilesForPrompt,P as formatMessagesForPrompt,k as formatPrompt,e as getAppEnv,I as getConnectionLevelSqlitePragmas,L as getPersistentSqlitePragmas,_ as humanizeNumber,f as ignoreEnoent,p as ignoreEnoentAsync,m as ignoreError,h as ignoreErrorAsync,v as mailTemplates,C as parseCommandLineArgs,S as parseMarkdownSections,T as quoteForShell,c as renderSectionChecklist,l as renderSectionTemplate,A as serializeForPrompt,j as serializeForPromptInTag,F as shuffle,u as sleep,E as toCodeBlock,D as toTildeCodeBlock,M as truncateForPrompt,g as withRetry,z as zenkakuAlphanumericalsToHankaku};
@@ -0,0 +1,5 @@
1
+ "use strict";function e(e){let t=m(e),n=[];for(let e=0;e<t.length;e++){let r=u(t[e]??``);if(!r)continue;let i=d(t,e+1,r);n.push({...r.language&&{language:r.language},code:t.slice(e+1,i).map(e=>p(e,r.indent)).join(`
2
+ `),isClosed:i<t.length}),e=i}return n}function t(e,t){let n=c(e);return!n||t?.length&&!t.some(e=>e.toLowerCase()===n.language)?e:n.code}const n=new Set([``,`markdown`,`md`]);function r(e,t){let n=i(e).map(e=>({...e,key:a(e.heading)})),r=[...new Set(t)].map(e=>({name:e,key:a(e)})),o=Object.create(null);for(let{name:e,key:t}of r){let i;for(let r of n)r.key===t&&(!i||r.depth<i.depth||r.depth===i.depth&&r.heading===e&&i.heading!==e)&&(i=r);i&&(i.heading!==e&&r.some(n=>n.name!==e&&n.key===t)||i.content&&(o[e]=i.content))}return o}function i(e){let t=c(e),r=t&&n.has(t.language)?t:void 0;if(r?.isWhole)return s(r.code);let i=s(e);return i.length===0&&r?s(r.code):i}function a(e){return o(o(e).replace(/^\d+(?:\.\d+)*(?:\.\s+|\)\s*|\s+)/u,``)).replaceAll(/\s+/gu,` `).toLowerCase()}function o(e){return e.replaceAll(/^[\s*_`~"'「」]+|[\s*_`~"'「」::]+$/gu,``)}function s(e){let t=m(e),n=l(t);return n.map((e,r)=>{let i=r+1;for(;i<n.length&&(n[i]?.depth??0)>e.depth;)i++;return{depth:e.depth,heading:e.text,content:t.slice(e.index+1,n[i]?.index).join(`
3
+ `).trim()}})}function c(e){let t=m(e.replace(/^\s*\n/u,``).trimEnd()),n=u(t[0]??``);if(!n)return;let r=t.length-1,i=r>0&&f(t[r]??``,n)?r:d(t,1,n);return{language:n.language,code:t.slice(1,i).map(e=>p(e,n.indent)).join(`
4
+ `),isWhole:i>=r}}function l(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??``,i=u(r);if(i){n=d(e,n+1,i);continue}let a=/^(#{1,6})(?:[ \t]+(.*))?$/u.exec(r);if(!a)continue;let o=(a[2]??``).replace(/(?:^|[ \t]+)#+[ \t]*$/u,``).trim().replaceAll(/(`+)(.+?)\1/gu,(e,t,n)=>n.startsWith(` `)&&n.endsWith(` `)?n.slice(1,-1):n);t.push({index:n,depth:a[1]?.length??1,text:o})}return t}function u(e){let t=/^( {0,3})(`{3,}|~{3,})(.*)$/u.exec(e),n=t?.[2],r=t?.[3]??``;if(!(!n||n.startsWith("`")&&r.includes("`")))return{char:n.charAt(0),length:n.length,indent:t[1]?.length??0,language:r.trim().split(/\s/u)[0]?.toLowerCase()??``}}function d(e,t,n){let r=t;for(;r<e.length&&!f(e[r]??``,n);)r++;return r}function f(e,t){let n=/^ {0,3}(`{3,}|~{3,})[ \t]*$/u.exec(e)?.[1];return n?.charAt(0)===t.char&&n.length>=t.length}function p(e,t){let n=0;for(;n<t&&e[n]===` `;)n++;return e.slice(n)}function m(e){return e.split(/\r?\n/u)}exports.extractCodeBlocks=e,exports.extractIfSingleOutermostCodeBlock=t,exports.extractSections=r,exports.parseMarkdownSections=i;
5
+ //# sourceMappingURL=markdown.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown.cjs","names":[],"sources":["../src/markdown.ts"],"sourcesContent":["export interface CodeBlock {\n /** The first word of the info string, lowercased; `undefined` when the fence has none. */\n language?: string;\n code: string;\n /** `false` when the text ends before the closing fence, e.g. because the LLM output was cut off. */\n isClosed: boolean;\n}\n\ninterface Fence {\n char: string;\n length: number;\n indent: number;\n language: string;\n}\n\n/**\n * Extracts the fenced code blocks (backticks or tildes, any fence length) of Markdown text such as an LLM response.\n * A block runs to the first closing fence of the same character that is at least as long as its opening fence,\n * so a longer fence can hold shorter fences. Only fences indented by at most three spaces are recognized; fences\n * inside block quotes, deeply nested list items, and indented code blocks are not.\n */\nexport function extractCodeBlocks(markdown: string): CodeBlock[] {\n const lines = splitLines(markdown);\n const blocks: CodeBlock[] = [];\n for (let index = 0; index < lines.length; index++) {\n const fence = parseOpeningFence(lines[index] ?? '');\n if (!fence) continue;\n const end = findClosingFence(lines, index + 1, fence);\n blocks.push({\n ...(fence.language && { language: fence.language }),\n code: lines\n .slice(index + 1, end)\n .map((line) => stripIndent(line, fence.indent))\n .join('\\n'),\n isClosed: end < lines.length,\n });\n index = end;\n }\n return blocks;\n}\n\n/**\n * Returns the contents of the code block that an LLM wrapped its whole response in, or `text` itself when the\n * response does not start with a fence or the fence's language is not one of a nonempty `languages` list\n * (compared case-insensitively). An omitted or empty list allows any language.\n * When the response also ends with a matching closing fence, everything between its first and last lines is returned,\n * so fences the LLM nested without lengthening the outer fence stay in the contents. Otherwise the first block is\n * returned and text after it is dropped; an unclosed block runs to the end of the text.\n */\nexport function extractIfSingleOutermostCodeBlock(text: string, languages?: readonly string[]): string {\n const block = findOutermostCodeBlock(text);\n if (!block) return text;\n if (languages?.length && !languages.some((language) => language.toLowerCase() === block.language)) return text;\n return block.code;\n}\n\nexport interface MarkdownSection {\n depth: number;\n /** The heading text with the closing `#` sequence and inline-code backticks removed. */\n heading: string;\n /** The source text up to the next heading at the same or a shallower depth, trimmed; subsections are included. */\n content: string;\n}\n\nconst WRAPPED_MARKDOWN_LANGUAGES = new Set(['', 'markdown', 'md']);\n\n/**\n * Extracts the content of the section headed by each of `names` from Markdown text such as an LLM response, keyed by\n * the given names. A heading matches a name when both are equal after removing decorations at their edges (such as\n * `**bold**`, backticks, and quotes), a leading number like `1.` or `2.1`, and a trailing colon, ignoring case and spacing;\n * headings at any depth are candidates.\n * Among matching headings, the shallowest wins, then one equal to the name as written, then the first; each heading\n * serves at most one name. When distinct requested names normalize alike, only exact matches at the shallowest\n * matching depth are returned. Missing, empty, or ambiguous sections are absent from the prototype-free result.\n */\nexport function extractSections<const Name extends string>(\n markdown: string,\n names: readonly Name[]\n): Partial<Record<Name, string>> {\n const candidates = parseMarkdownSections(markdown).map((section) => ({\n ...section,\n key: normalizeHeading(section.heading),\n }));\n const requested = [...new Set(names)].map((name) => ({ name, key: normalizeHeading(name) }));\n const sections: Partial<Record<Name, string>> = Object.create(null);\n for (const { name, key } of requested) {\n let best: (typeof candidates)[number] | undefined;\n for (const candidate of candidates) {\n if (candidate.key !== key) continue;\n if (\n !best ||\n candidate.depth < best.depth ||\n (candidate.depth === best.depth && candidate.heading === name && best.heading !== name)\n ) {\n best = candidate;\n }\n }\n if (!best) continue;\n if (best.heading !== name && requested.some((other) => other.name !== name && other.key === key)) continue;\n if (best.content) sections[name] = best.content;\n }\n return sections;\n}\n\n/**\n * Returns every ATX heading of Markdown text in order, with the source text under it.\n * Only headings starting at the beginning of a line outside fenced code blocks count; setext headings (underlined\n * with `=` or `-`) are ignored. A whole-response `markdown`, `md`, or unlabeled wrapper is read inside as\n * `extractIfSingleOutermostCodeBlock` finds it, preserving nested fences. A leading wrapper followed by prose is\n * also read inside, but only when there are no headings outside fences.\n */\nexport function parseMarkdownSections(markdown: string): MarkdownSection[] {\n const block = findOutermostCodeBlock(markdown);\n const wrapper = block && WRAPPED_MARKDOWN_LANGUAGES.has(block.language) ? block : undefined;\n if (wrapper?.isWhole) return splitSections(wrapper.code);\n const sections = splitSections(markdown);\n return sections.length === 0 && wrapper ? splitSections(wrapper.code) : sections;\n}\n\nfunction normalizeHeading(heading: string): string {\n return stripHeadingEdges(stripHeadingEdges(heading).replace(/^\\d+(?:\\.\\d+)*(?:\\.\\s+|\\)\\s*|\\s+)/u, ''))\n .replaceAll(/\\s+/gu, ' ')\n .toLowerCase();\n}\n\nfunction stripHeadingEdges(text: string): string {\n // Only the edges: `_` and `*` inside a heading belong to names such as `my_file.py`.\n return text.replaceAll(/^[\\s*_`~\"'「」]+|[\\s*_`~\"'「」::]+$/gu, '');\n}\n\nfunction splitSections(markdown: string): MarkdownSection[] {\n const lines = splitLines(markdown);\n const headings = findHeadings(lines);\n return headings.map((heading, index) => {\n let nextIndex = index + 1;\n while (nextIndex < headings.length && (headings[nextIndex]?.depth ?? 0) > heading.depth) nextIndex++;\n return {\n depth: heading.depth,\n heading: heading.text,\n content: lines\n .slice(heading.index + 1, headings[nextIndex]?.index)\n .join('\\n')\n .trim(),\n };\n });\n}\n\nfunction findOutermostCodeBlock(text: string): { language: string; code: string; isWhole: boolean } | undefined {\n // Keep the opening fence's indentation, which is stripped from the contents.\n const lines = splitLines(text.replace(/^\\s*\\n/u, '').trimEnd());\n const fence = parseOpeningFence(lines[0] ?? '');\n if (!fence) return;\n const lastIndex = lines.length - 1;\n const end =\n lastIndex > 0 && isClosingFence(lines[lastIndex] ?? '', fence) ? lastIndex : findClosingFence(lines, 1, fence);\n return {\n language: fence.language,\n code: lines\n .slice(1, end)\n .map((line) => stripIndent(line, fence.indent))\n .join('\\n'),\n isWhole: end >= lastIndex,\n };\n}\n\nfunction findHeadings(lines: readonly string[]): { index: number; depth: number; text: string }[] {\n const headings: { index: number; depth: number; text: string }[] = [];\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] ?? '';\n const fence = parseOpeningFence(line);\n if (fence) {\n index = findClosingFence(lines, index + 1, fence);\n continue;\n }\n const match = /^(#{1,6})(?:[ \\t]+(.*))?$/u.exec(line);\n if (!match) continue;\n const text = (match[2] ?? '')\n // The closing sequence of an ATX heading needs a space before it, so `# C#` keeps its `#`.\n .replace(/(?:^|[ \\t]+)#+[ \\t]*$/u, '')\n .trim()\n .replaceAll(/(`+)(.+?)\\1/gu, (_match, _delimiter: string, content: string) =>\n content.startsWith(' ') && content.endsWith(' ') ? content.slice(1, -1) : content\n );\n headings.push({ index, depth: match[1]?.length ?? 1, text });\n }\n return headings;\n}\n\nfunction parseOpeningFence(line: string): Fence | undefined {\n const match = /^( {0,3})(`{3,}|~{3,})(.*)$/u.exec(line);\n const fence = match?.[2];\n const info = match?.[3] ?? '';\n // A backtick in the info string makes the line inline code instead of a fence.\n if (!fence || (fence.startsWith('`') && info.includes('`'))) return;\n return {\n char: fence.charAt(0),\n length: fence.length,\n indent: match[1]?.length ?? 0,\n language: info.trim().split(/\\s/u)[0]?.toLowerCase() ?? '',\n };\n}\n\n/** Returns the index of the line closing `fence`, or the number of lines when it is never closed. */\nfunction findClosingFence(lines: readonly string[], start: number, fence: Fence): number {\n let index = start;\n while (index < lines.length && !isClosingFence(lines[index] ?? '', fence)) index++;\n return index;\n}\n\nfunction isClosingFence(line: string, fence: Fence): boolean {\n const closer = /^ {0,3}(`{3,}|~{3,})[ \\t]*$/u.exec(line)?.[1];\n return closer?.charAt(0) === fence.char && closer.length >= fence.length;\n}\n\nfunction stripIndent(line: string, indent: number): string {\n let index = 0;\n while (index < indent && line[index] === ' ') index++;\n return line.slice(index);\n}\n\nfunction splitLines(text: string): string[] {\n return text.split(/\\r?\\n/u);\n}\n"],"mappings":"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"}
@@ -0,0 +1,48 @@
1
+ export interface CodeBlock {
2
+ /** The first word of the info string, lowercased; `undefined` when the fence has none. */
3
+ language?: string;
4
+ code: string;
5
+ /** `false` when the text ends before the closing fence, e.g. because the LLM output was cut off. */
6
+ isClosed: boolean;
7
+ }
8
+ /**
9
+ * Extracts the fenced code blocks (backticks or tildes, any fence length) of Markdown text such as an LLM response.
10
+ * A block runs to the first closing fence of the same character that is at least as long as its opening fence,
11
+ * so a longer fence can hold shorter fences. Only fences indented by at most three spaces are recognized; fences
12
+ * inside block quotes, deeply nested list items, and indented code blocks are not.
13
+ */
14
+ export declare function extractCodeBlocks(markdown: string): CodeBlock[];
15
+ /**
16
+ * Returns the contents of the code block that an LLM wrapped its whole response in, or `text` itself when the
17
+ * response does not start with a fence or the fence's language is not one of a nonempty `languages` list
18
+ * (compared case-insensitively). An omitted or empty list allows any language.
19
+ * When the response also ends with a matching closing fence, everything between its first and last lines is returned,
20
+ * so fences the LLM nested without lengthening the outer fence stay in the contents. Otherwise the first block is
21
+ * returned and text after it is dropped; an unclosed block runs to the end of the text.
22
+ */
23
+ export declare function extractIfSingleOutermostCodeBlock(text: string, languages?: readonly string[]): string;
24
+ export interface MarkdownSection {
25
+ depth: number;
26
+ /** The heading text with the closing `#` sequence and inline-code backticks removed. */
27
+ heading: string;
28
+ /** The source text up to the next heading at the same or a shallower depth, trimmed; subsections are included. */
29
+ content: string;
30
+ }
31
+ /**
32
+ * Extracts the content of the section headed by each of `names` from Markdown text such as an LLM response, keyed by
33
+ * the given names. A heading matches a name when both are equal after removing decorations at their edges (such as
34
+ * `**bold**`, backticks, and quotes), a leading number like `1.` or `2.1`, and a trailing colon, ignoring case and spacing;
35
+ * headings at any depth are candidates.
36
+ * Among matching headings, the shallowest wins, then one equal to the name as written, then the first; each heading
37
+ * serves at most one name. When distinct requested names normalize alike, only exact matches at the shallowest
38
+ * matching depth are returned. Missing, empty, or ambiguous sections are absent from the prototype-free result.
39
+ */
40
+ export declare function extractSections<const Name extends string>(markdown: string, names: readonly Name[]): Partial<Record<Name, string>>;
41
+ /**
42
+ * Returns every ATX heading of Markdown text in order, with the source text under it.
43
+ * Only headings starting at the beginning of a line outside fenced code blocks count; setext headings (underlined
44
+ * with `=` or `-`) are ignored. A whole-response `markdown`, `md`, or unlabeled wrapper is read inside as
45
+ * `extractIfSingleOutermostCodeBlock` finds it, preserving nested fences. A leading wrapper followed by prose is
46
+ * also read inside, but only when there are no headings outside fences.
47
+ */
48
+ export declare function parseMarkdownSections(markdown: string): MarkdownSection[];
@@ -0,0 +1,5 @@
1
+ function e(e){let t=m(e),n=[];for(let e=0;e<t.length;e++){let r=u(t[e]??``);if(!r)continue;let i=d(t,e+1,r);n.push({...r.language&&{language:r.language},code:t.slice(e+1,i).map(e=>p(e,r.indent)).join(`
2
+ `),isClosed:i<t.length}),e=i}return n}function t(e,t){let n=c(e);return!n||t?.length&&!t.some(e=>e.toLowerCase()===n.language)?e:n.code}const n=new Set([``,`markdown`,`md`]);function r(e,t){let n=i(e).map(e=>({...e,key:a(e.heading)})),r=[...new Set(t)].map(e=>({name:e,key:a(e)})),o=Object.create(null);for(let{name:e,key:t}of r){let i;for(let r of n)r.key===t&&(!i||r.depth<i.depth||r.depth===i.depth&&r.heading===e&&i.heading!==e)&&(i=r);i&&(i.heading!==e&&r.some(n=>n.name!==e&&n.key===t)||i.content&&(o[e]=i.content))}return o}function i(e){let t=c(e),r=t&&n.has(t.language)?t:void 0;if(r?.isWhole)return s(r.code);let i=s(e);return i.length===0&&r?s(r.code):i}function a(e){return o(o(e).replace(/^\d+(?:\.\d+)*(?:\.\s+|\)\s*|\s+)/u,``)).replaceAll(/\s+/gu,` `).toLowerCase()}function o(e){return e.replaceAll(/^[\s*_`~"'「」]+|[\s*_`~"'「」::]+$/gu,``)}function s(e){let t=m(e),n=l(t);return n.map((e,r)=>{let i=r+1;for(;i<n.length&&(n[i]?.depth??0)>e.depth;)i++;return{depth:e.depth,heading:e.text,content:t.slice(e.index+1,n[i]?.index).join(`
3
+ `).trim()}})}function c(e){let t=m(e.replace(/^\s*\n/u,``).trimEnd()),n=u(t[0]??``);if(!n)return;let r=t.length-1,i=r>0&&f(t[r]??``,n)?r:d(t,1,n);return{language:n.language,code:t.slice(1,i).map(e=>p(e,n.indent)).join(`
4
+ `),isWhole:i>=r}}function l(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??``,i=u(r);if(i){n=d(e,n+1,i);continue}let a=/^(#{1,6})(?:[ \t]+(.*))?$/u.exec(r);if(!a)continue;let o=(a[2]??``).replace(/(?:^|[ \t]+)#+[ \t]*$/u,``).trim().replaceAll(/(`+)(.+?)\1/gu,(e,t,n)=>n.startsWith(` `)&&n.endsWith(` `)?n.slice(1,-1):n);t.push({index:n,depth:a[1]?.length??1,text:o})}return t}function u(e){let t=/^( {0,3})(`{3,}|~{3,})(.*)$/u.exec(e),n=t?.[2],r=t?.[3]??``;if(!(!n||n.startsWith("`")&&r.includes("`")))return{char:n.charAt(0),length:n.length,indent:t[1]?.length??0,language:r.trim().split(/\s/u)[0]?.toLowerCase()??``}}function d(e,t,n){let r=t;for(;r<e.length&&!f(e[r]??``,n);)r++;return r}function f(e,t){let n=/^ {0,3}(`{3,}|~{3,})[ \t]*$/u.exec(e)?.[1];return n?.charAt(0)===t.char&&n.length>=t.length}function p(e,t){let n=0;for(;n<t&&e[n]===` `;)n++;return e.slice(n)}function m(e){return e.split(/\r?\n/u)}export{e as extractCodeBlocks,t as extractIfSingleOutermostCodeBlock,r as extractSections,i as parseMarkdownSections};
5
+ //# sourceMappingURL=markdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown.js","names":[],"sources":["../src/markdown.ts"],"sourcesContent":["export interface CodeBlock {\n /** The first word of the info string, lowercased; `undefined` when the fence has none. */\n language?: string;\n code: string;\n /** `false` when the text ends before the closing fence, e.g. because the LLM output was cut off. */\n isClosed: boolean;\n}\n\ninterface Fence {\n char: string;\n length: number;\n indent: number;\n language: string;\n}\n\n/**\n * Extracts the fenced code blocks (backticks or tildes, any fence length) of Markdown text such as an LLM response.\n * A block runs to the first closing fence of the same character that is at least as long as its opening fence,\n * so a longer fence can hold shorter fences. Only fences indented by at most three spaces are recognized; fences\n * inside block quotes, deeply nested list items, and indented code blocks are not.\n */\nexport function extractCodeBlocks(markdown: string): CodeBlock[] {\n const lines = splitLines(markdown);\n const blocks: CodeBlock[] = [];\n for (let index = 0; index < lines.length; index++) {\n const fence = parseOpeningFence(lines[index] ?? '');\n if (!fence) continue;\n const end = findClosingFence(lines, index + 1, fence);\n blocks.push({\n ...(fence.language && { language: fence.language }),\n code: lines\n .slice(index + 1, end)\n .map((line) => stripIndent(line, fence.indent))\n .join('\\n'),\n isClosed: end < lines.length,\n });\n index = end;\n }\n return blocks;\n}\n\n/**\n * Returns the contents of the code block that an LLM wrapped its whole response in, or `text` itself when the\n * response does not start with a fence or the fence's language is not one of a nonempty `languages` list\n * (compared case-insensitively). An omitted or empty list allows any language.\n * When the response also ends with a matching closing fence, everything between its first and last lines is returned,\n * so fences the LLM nested without lengthening the outer fence stay in the contents. Otherwise the first block is\n * returned and text after it is dropped; an unclosed block runs to the end of the text.\n */\nexport function extractIfSingleOutermostCodeBlock(text: string, languages?: readonly string[]): string {\n const block = findOutermostCodeBlock(text);\n if (!block) return text;\n if (languages?.length && !languages.some((language) => language.toLowerCase() === block.language)) return text;\n return block.code;\n}\n\nexport interface MarkdownSection {\n depth: number;\n /** The heading text with the closing `#` sequence and inline-code backticks removed. */\n heading: string;\n /** The source text up to the next heading at the same or a shallower depth, trimmed; subsections are included. */\n content: string;\n}\n\nconst WRAPPED_MARKDOWN_LANGUAGES = new Set(['', 'markdown', 'md']);\n\n/**\n * Extracts the content of the section headed by each of `names` from Markdown text such as an LLM response, keyed by\n * the given names. A heading matches a name when both are equal after removing decorations at their edges (such as\n * `**bold**`, backticks, and quotes), a leading number like `1.` or `2.1`, and a trailing colon, ignoring case and spacing;\n * headings at any depth are candidates.\n * Among matching headings, the shallowest wins, then one equal to the name as written, then the first; each heading\n * serves at most one name. When distinct requested names normalize alike, only exact matches at the shallowest\n * matching depth are returned. Missing, empty, or ambiguous sections are absent from the prototype-free result.\n */\nexport function extractSections<const Name extends string>(\n markdown: string,\n names: readonly Name[]\n): Partial<Record<Name, string>> {\n const candidates = parseMarkdownSections(markdown).map((section) => ({\n ...section,\n key: normalizeHeading(section.heading),\n }));\n const requested = [...new Set(names)].map((name) => ({ name, key: normalizeHeading(name) }));\n const sections: Partial<Record<Name, string>> = Object.create(null);\n for (const { name, key } of requested) {\n let best: (typeof candidates)[number] | undefined;\n for (const candidate of candidates) {\n if (candidate.key !== key) continue;\n if (\n !best ||\n candidate.depth < best.depth ||\n (candidate.depth === best.depth && candidate.heading === name && best.heading !== name)\n ) {\n best = candidate;\n }\n }\n if (!best) continue;\n if (best.heading !== name && requested.some((other) => other.name !== name && other.key === key)) continue;\n if (best.content) sections[name] = best.content;\n }\n return sections;\n}\n\n/**\n * Returns every ATX heading of Markdown text in order, with the source text under it.\n * Only headings starting at the beginning of a line outside fenced code blocks count; setext headings (underlined\n * with `=` or `-`) are ignored. A whole-response `markdown`, `md`, or unlabeled wrapper is read inside as\n * `extractIfSingleOutermostCodeBlock` finds it, preserving nested fences. A leading wrapper followed by prose is\n * also read inside, but only when there are no headings outside fences.\n */\nexport function parseMarkdownSections(markdown: string): MarkdownSection[] {\n const block = findOutermostCodeBlock(markdown);\n const wrapper = block && WRAPPED_MARKDOWN_LANGUAGES.has(block.language) ? block : undefined;\n if (wrapper?.isWhole) return splitSections(wrapper.code);\n const sections = splitSections(markdown);\n return sections.length === 0 && wrapper ? splitSections(wrapper.code) : sections;\n}\n\nfunction normalizeHeading(heading: string): string {\n return stripHeadingEdges(stripHeadingEdges(heading).replace(/^\\d+(?:\\.\\d+)*(?:\\.\\s+|\\)\\s*|\\s+)/u, ''))\n .replaceAll(/\\s+/gu, ' ')\n .toLowerCase();\n}\n\nfunction stripHeadingEdges(text: string): string {\n // Only the edges: `_` and `*` inside a heading belong to names such as `my_file.py`.\n return text.replaceAll(/^[\\s*_`~\"'「」]+|[\\s*_`~\"'「」::]+$/gu, '');\n}\n\nfunction splitSections(markdown: string): MarkdownSection[] {\n const lines = splitLines(markdown);\n const headings = findHeadings(lines);\n return headings.map((heading, index) => {\n let nextIndex = index + 1;\n while (nextIndex < headings.length && (headings[nextIndex]?.depth ?? 0) > heading.depth) nextIndex++;\n return {\n depth: heading.depth,\n heading: heading.text,\n content: lines\n .slice(heading.index + 1, headings[nextIndex]?.index)\n .join('\\n')\n .trim(),\n };\n });\n}\n\nfunction findOutermostCodeBlock(text: string): { language: string; code: string; isWhole: boolean } | undefined {\n // Keep the opening fence's indentation, which is stripped from the contents.\n const lines = splitLines(text.replace(/^\\s*\\n/u, '').trimEnd());\n const fence = parseOpeningFence(lines[0] ?? '');\n if (!fence) return;\n const lastIndex = lines.length - 1;\n const end =\n lastIndex > 0 && isClosingFence(lines[lastIndex] ?? '', fence) ? lastIndex : findClosingFence(lines, 1, fence);\n return {\n language: fence.language,\n code: lines\n .slice(1, end)\n .map((line) => stripIndent(line, fence.indent))\n .join('\\n'),\n isWhole: end >= lastIndex,\n };\n}\n\nfunction findHeadings(lines: readonly string[]): { index: number; depth: number; text: string }[] {\n const headings: { index: number; depth: number; text: string }[] = [];\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] ?? '';\n const fence = parseOpeningFence(line);\n if (fence) {\n index = findClosingFence(lines, index + 1, fence);\n continue;\n }\n const match = /^(#{1,6})(?:[ \\t]+(.*))?$/u.exec(line);\n if (!match) continue;\n const text = (match[2] ?? '')\n // The closing sequence of an ATX heading needs a space before it, so `# C#` keeps its `#`.\n .replace(/(?:^|[ \\t]+)#+[ \\t]*$/u, '')\n .trim()\n .replaceAll(/(`+)(.+?)\\1/gu, (_match, _delimiter: string, content: string) =>\n content.startsWith(' ') && content.endsWith(' ') ? content.slice(1, -1) : content\n );\n headings.push({ index, depth: match[1]?.length ?? 1, text });\n }\n return headings;\n}\n\nfunction parseOpeningFence(line: string): Fence | undefined {\n const match = /^( {0,3})(`{3,}|~{3,})(.*)$/u.exec(line);\n const fence = match?.[2];\n const info = match?.[3] ?? '';\n // A backtick in the info string makes the line inline code instead of a fence.\n if (!fence || (fence.startsWith('`') && info.includes('`'))) return;\n return {\n char: fence.charAt(0),\n length: fence.length,\n indent: match[1]?.length ?? 0,\n language: info.trim().split(/\\s/u)[0]?.toLowerCase() ?? '',\n };\n}\n\n/** Returns the index of the line closing `fence`, or the number of lines when it is never closed. */\nfunction findClosingFence(lines: readonly string[], start: number, fence: Fence): number {\n let index = start;\n while (index < lines.length && !isClosingFence(lines[index] ?? '', fence)) index++;\n return index;\n}\n\nfunction isClosingFence(line: string, fence: Fence): boolean {\n const closer = /^ {0,3}(`{3,}|~{3,})[ \\t]*$/u.exec(line)?.[1];\n return closer?.charAt(0) === fence.char && closer.length >= fence.length;\n}\n\nfunction stripIndent(line: string, indent: number): string {\n let index = 0;\n while (index < indent && line[index] === ' ') index++;\n return line.slice(index);\n}\n\nfunction splitLines(text: string): string[] {\n return text.split(/\\r?\\n/u);\n}\n"],"mappings":"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"}
@@ -0,0 +1,7 @@
1
+ "use strict";const e=require("./text.cjs"),t=require("./prompt.cjs");function n(t,n=1){let i=`#`.repeat(n);return t.map(t=>`${i} ${r(t.path)}\n\n${e.toCodeBlock(t.data.replaceAll(/\r\n?/gu,`
2
+ `).trimEnd())}`).join(`
3
+
4
+ `)}function r(e){let t=1;for(let n of e.matchAll(/`+/gu))t=Math.max(t,n[0].length+1);let n="`".repeat(t);return`${n} ${e} ${n}`}function i(e){let n=[...new Set([`system`,`developer`,`user`,`assistant`,`tool`,...e.map(e=>e.role)])];return e.map(e=>{let r=e.content;for(let e of n)r=t.escapePromptTag(r,e);return`<${e.role}>\n${r}\n</${e.role}>`}).join(`
5
+
6
+ `)}exports.formatFilesForPrompt=n,exports.formatMessagesForPrompt=i;
7
+ //# sourceMappingURL=promptFormatters.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promptFormatters.cjs","names":["toCodeBlock","escapePromptTag"],"sources":["../src/promptFormatters.ts"],"sourcesContent":["import { escapePromptTag } from './prompt.js';\nimport { toCodeBlock } from './text.js';\n\n/**\n * Renders files as Markdown sections for an LLM prompt: a heading holding the single-line path in inline code,\n * followed by the file contents in a code block whose fence the contents cannot close. Line endings are normalized\n * to LF and trailing whitespace is removed.\n * The output reads back with `extractSections` (keyed by path) and `extractIfSingleOutermostCodeBlock`, so an\n * LLM can be asked to answer in the same format.\n */\nexport function formatFilesForPrompt(files: readonly { path: string; data: string }[], headingLevel = 1): string {\n const headingMarker = '#'.repeat(headingLevel);\n return files\n .map(\n (file) =>\n `${headingMarker} ${formatPath(file.path)}\\n\\n${toCodeBlock(file.data.replaceAll(/\\r\\n?/gu, '\\n').trimEnd())}`\n )\n .join('\\n\\n');\n}\n\nfunction formatPath(path: string): string {\n let length = 1;\n for (const match of path.matchAll(/`+/gu)) length = Math.max(length, match[0].length + 1);\n const delimiter = '`'.repeat(length);\n return `${delimiter} ${path} ${delimiter}`;\n}\n\n/**\n * Renders chat messages as `<role>` elements separated by blank lines, e.g. to embed a conversation log in a prompt.\n * Escapes system, developer, user, assistant, tool, and every supplied role's tags in message contents.\n * Roles must be trusted literal tag names supplied by the caller. This preserves delimiters, not instruction priority.\n * To wrap the result in another element, escape that tag in the result with `escapePromptTag`.\n */\nexport function formatMessagesForPrompt(messages: readonly { role: string; content: string }[]): string {\n const roles = [\n ...new Set(['system', 'developer', 'user', 'assistant', 'tool', ...messages.map((message) => message.role)]),\n ];\n return messages\n .map((message) => {\n let content = message.content;\n for (const role of roles) content = escapePromptTag(content, role);\n return `<${message.role}>\\n${content}\\n</${message.role}>`;\n })\n .join('\\n\\n');\n}\n"],"mappings":"qEAUA,SAAgB,EAAqB,EAAkD,EAAe,EAAW,CAC/G,IAAM,EAAgB,IAAI,OAAO,CAAY,EAC7C,OAAO,EACJ,IACE,GACC,GAAG,EAAc,GAAG,EAAW,EAAK,IAAI,EAAE,MAAMA,EAAAA,YAAY,EAAK,KAAK,WAAW,UAAW;CAAI,CAAC,CAAC,QAAQ,CAAC,GAC/G,CAAC,CACA,KAAK;;CAAM,CAChB,CAEA,SAAS,EAAW,EAAsB,CACxC,IAAI,EAAS,EACb,IAAK,IAAM,KAAS,EAAK,SAAS,MAAM,EAAG,EAAS,KAAK,IAAI,EAAQ,EAAM,EAAE,CAAC,OAAS,CAAC,EACxF,IAAM,EAAY,IAAI,OAAO,CAAM,EACnC,MAAO,GAAG,EAAU,GAAG,EAAK,GAAG,GACjC,CAQA,SAAgB,EAAwB,EAAgE,CACtG,IAAM,EAAQ,CACZ,GAAG,IAAI,IAAI,CAAC,SAAU,YAAa,OAAQ,YAAa,OAAQ,GAAG,EAAS,IAAK,GAAY,EAAQ,IAAI,CAAC,CAAC,CAC7G,EACA,OAAO,EACJ,IAAK,GAAY,CAChB,IAAI,EAAU,EAAQ,QACtB,IAAK,IAAM,KAAQ,EAAO,EAAUC,EAAAA,gBAAgB,EAAS,CAAI,EACjE,MAAO,IAAI,EAAQ,KAAK,KAAK,EAAQ,MAAM,EAAQ,KAAK,EAC1D,CAAC,CAAC,CACD,KAAK;;CAAM,CAChB"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Renders files as Markdown sections for an LLM prompt: a heading holding the single-line path in inline code,
3
+ * followed by the file contents in a code block whose fence the contents cannot close. Line endings are normalized
4
+ * to LF and trailing whitespace is removed.
5
+ * The output reads back with `extractSections` (keyed by path) and `extractIfSingleOutermostCodeBlock`, so an
6
+ * LLM can be asked to answer in the same format.
7
+ */
8
+ export declare function formatFilesForPrompt(files: readonly {
9
+ path: string;
10
+ data: string;
11
+ }[], headingLevel?: number): string;
12
+ /**
13
+ * Renders chat messages as `<role>` elements separated by blank lines, e.g. to embed a conversation log in a prompt.
14
+ * Escapes system, developer, user, assistant, tool, and every supplied role's tags in message contents.
15
+ * Roles must be trusted literal tag names supplied by the caller. This preserves delimiters, not instruction priority.
16
+ * To wrap the result in another element, escape that tag in the result with `escapePromptTag`.
17
+ */
18
+ export declare function formatMessagesForPrompt(messages: readonly {
19
+ role: string;
20
+ content: string;
21
+ }[]): string;
@@ -0,0 +1,7 @@
1
+ import{toCodeBlock as e}from"./text.js";import{escapePromptTag as t}from"./prompt.js";function n(t,n=1){let i=`#`.repeat(n);return t.map(t=>`${i} ${r(t.path)}\n\n${e(t.data.replaceAll(/\r\n?/gu,`
2
+ `).trimEnd())}`).join(`
3
+
4
+ `)}function r(e){let t=1;for(let n of e.matchAll(/`+/gu))t=Math.max(t,n[0].length+1);let n="`".repeat(t);return`${n} ${e} ${n}`}function i(e){let n=[...new Set([`system`,`developer`,`user`,`assistant`,`tool`,...e.map(e=>e.role)])];return e.map(e=>{let r=e.content;for(let e of n)r=t(r,e);return`<${e.role}>\n${r}\n</${e.role}>`}).join(`
5
+
6
+ `)}export{n as formatFilesForPrompt,i as formatMessagesForPrompt};
7
+ //# sourceMappingURL=promptFormatters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promptFormatters.js","names":[],"sources":["../src/promptFormatters.ts"],"sourcesContent":["import { escapePromptTag } from './prompt.js';\nimport { toCodeBlock } from './text.js';\n\n/**\n * Renders files as Markdown sections for an LLM prompt: a heading holding the single-line path in inline code,\n * followed by the file contents in a code block whose fence the contents cannot close. Line endings are normalized\n * to LF and trailing whitespace is removed.\n * The output reads back with `extractSections` (keyed by path) and `extractIfSingleOutermostCodeBlock`, so an\n * LLM can be asked to answer in the same format.\n */\nexport function formatFilesForPrompt(files: readonly { path: string; data: string }[], headingLevel = 1): string {\n const headingMarker = '#'.repeat(headingLevel);\n return files\n .map(\n (file) =>\n `${headingMarker} ${formatPath(file.path)}\\n\\n${toCodeBlock(file.data.replaceAll(/\\r\\n?/gu, '\\n').trimEnd())}`\n )\n .join('\\n\\n');\n}\n\nfunction formatPath(path: string): string {\n let length = 1;\n for (const match of path.matchAll(/`+/gu)) length = Math.max(length, match[0].length + 1);\n const delimiter = '`'.repeat(length);\n return `${delimiter} ${path} ${delimiter}`;\n}\n\n/**\n * Renders chat messages as `<role>` elements separated by blank lines, e.g. to embed a conversation log in a prompt.\n * Escapes system, developer, user, assistant, tool, and every supplied role's tags in message contents.\n * Roles must be trusted literal tag names supplied by the caller. This preserves delimiters, not instruction priority.\n * To wrap the result in another element, escape that tag in the result with `escapePromptTag`.\n */\nexport function formatMessagesForPrompt(messages: readonly { role: string; content: string }[]): string {\n const roles = [\n ...new Set(['system', 'developer', 'user', 'assistant', 'tool', ...messages.map((message) => message.role)]),\n ];\n return messages\n .map((message) => {\n let content = message.content;\n for (const role of roles) content = escapePromptTag(content, role);\n return `<${message.role}>\\n${content}\\n</${message.role}>`;\n })\n .join('\\n\\n');\n}\n"],"mappings":"sFAUA,SAAgB,EAAqB,EAAkD,EAAe,EAAW,CAC/G,IAAM,EAAgB,IAAI,OAAO,CAAY,EAC7C,OAAO,EACJ,IACE,GACC,GAAG,EAAc,GAAG,EAAW,EAAK,IAAI,EAAE,MAAM,EAAY,EAAK,KAAK,WAAW,UAAW;CAAI,CAAC,CAAC,QAAQ,CAAC,GAC/G,CAAC,CACA,KAAK;;CAAM,CAChB,CAEA,SAAS,EAAW,EAAsB,CACxC,IAAI,EAAS,EACb,IAAK,IAAM,KAAS,EAAK,SAAS,MAAM,EAAG,EAAS,KAAK,IAAI,EAAQ,EAAM,EAAE,CAAC,OAAS,CAAC,EACxF,IAAM,EAAY,IAAI,OAAO,CAAM,EACnC,MAAO,GAAG,EAAU,GAAG,EAAK,GAAG,GACjC,CAQA,SAAgB,EAAwB,EAAgE,CACtG,IAAM,EAAQ,CACZ,GAAG,IAAI,IAAI,CAAC,SAAU,YAAa,OAAQ,YAAa,OAAQ,GAAG,EAAS,IAAK,GAAY,EAAQ,IAAI,CAAC,CAAC,CAC7G,EACA,OAAO,EACJ,IAAK,GAAY,CAChB,IAAI,EAAU,EAAQ,QACtB,IAAK,IAAM,KAAQ,EAAO,EAAU,EAAgB,EAAS,CAAI,EACjE,MAAO,IAAI,EAAQ,KAAK,KAAK,EAAQ,MAAM,EAAQ,KAAK,EAC1D,CAAC,CAAC,CACD,KAAK;;CAAM,CAChB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@willbooster/shared-lib",
3
- "version": "10.8.0",
3
+ "version": "10.9.1",
4
4
  "description": "Shared library for WillBooster projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -49,8 +49,8 @@
49
49
  "@types/node": "26.5.1",
50
50
  "@willbooster/oxfmt-config": "1.2.2",
51
51
  "@willbooster/oxlint-config": "1.4.8",
52
- "@willbooster/wb": "22.4.0",
53
- "build-ts": "21.0.14",
52
+ "@willbooster/wb": "22.6.0",
53
+ "build-ts": "21.0.16",
54
54
  "oxfmt": "0.67.0",
55
55
  "oxlint": "1.82.0",
56
56
  "oxlint-tsgolint": "7.0.2001",