@directive-run/core 0.1.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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -0
  3. package/dist/adapter-utils.cjs +2 -0
  4. package/dist/adapter-utils.cjs.map +1 -0
  5. package/dist/adapter-utils.d.cts +230 -0
  6. package/dist/adapter-utils.d.ts +230 -0
  7. package/dist/adapter-utils.js +2 -0
  8. package/dist/adapter-utils.js.map +1 -0
  9. package/dist/index.cjs +35 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.cts +2016 -0
  12. package/dist/index.d.ts +2016 -0
  13. package/dist/index.js +35 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/migration.cjs +25 -0
  16. package/dist/migration.cjs.map +1 -0
  17. package/dist/migration.d.cts +109 -0
  18. package/dist/migration.d.ts +109 -0
  19. package/dist/migration.js +25 -0
  20. package/dist/migration.js.map +1 -0
  21. package/dist/plugins/index.cjs +3 -0
  22. package/dist/plugins/index.cjs.map +1 -0
  23. package/dist/plugins/index.d.cts +697 -0
  24. package/dist/plugins/index.d.ts +697 -0
  25. package/dist/plugins/index.js +3 -0
  26. package/dist/plugins/index.js.map +1 -0
  27. package/dist/plugins-CcwEXXMS.d.cts +1876 -0
  28. package/dist/plugins-CcwEXXMS.d.ts +1876 -0
  29. package/dist/testing.cjs +12 -0
  30. package/dist/testing.cjs.map +1 -0
  31. package/dist/testing.d.cts +235 -0
  32. package/dist/testing.d.ts +235 -0
  33. package/dist/testing.js +12 -0
  34. package/dist/testing.js.map +1 -0
  35. package/dist/utils-4JrY5fk9.d.cts +198 -0
  36. package/dist/utils-4JrY5fk9.d.ts +198 -0
  37. package/dist/worker.cjs +12 -0
  38. package/dist/worker.cjs.map +1 -0
  39. package/dist/worker.d.cts +241 -0
  40. package/dist/worker.d.ts +241 -0
  41. package/dist/worker.js +12 -0
  42. package/dist/worker.js.map +1 -0
  43. package/package.json +85 -0
@@ -0,0 +1,25 @@
1
+ 'use strict';function m(e){let t={},s={},i={};for(let[n,a]of Object.entries(e.initialState))t[n]=p(a);for(let n of Object.keys(e.reducers))n.includes("By")||n.includes("Set")||n.includes("With")?(s[n]={payload:"t.any()"},i[n]=`(facts, { payload }) => {
2
+ // TODO: Implement ${n}
3
+ }`):(s[n]={},i[n]=`(facts) => {
4
+ // TODO: Implement ${n}
5
+ }`);let c=`(facts) => {
6
+ ${Object.entries(e.initialState).map(([n,a])=>` facts.${n} = ${JSON.stringify(a)};`).join(`
7
+ `)}
8
+ }`;return {name:e.name,facts:t,derivations:{},events:s,requirements:{},initCode:c,deriveCode:{},eventsCode:i}}function h(e){let t={},s={},i={};for(let[n,a]of Object.entries(e.state))t[n]=p(a);for(let n of Object.keys(e.actions))s[n]={},i[n]=`(facts) => {
9
+ // TODO: Implement ${n}
10
+ }`;let c=`(facts) => {
11
+ ${Object.entries(e.state).map(([n,a])=>` facts.${n} = ${JSON.stringify(a)};`).join(`
12
+ `)}
13
+ }`;return {name:"store",facts:t,derivations:{},events:s,requirements:{},initCode:c,deriveCode:{},eventsCode:i}}function y(e){let t={state:`t.string<${Object.keys(e.states).map(r=>`'${r}'`).join(" | ")}>()`},s={},i={},f={},c={};if(e.context)for(let[r,o]of Object.entries(e.context))t[r]=p(o);for(let r of Object.keys(e.states)){let o=`is${l(r)}`;s[o]="t.boolean()",i[o]=`(facts) => facts.state === '${r}'`;}let n=new Map;for(let[r,o]of Object.entries(e.states))if(o.on)for(let[d,u]of Object.entries(o.on)){n.has(d)||n.set(d,new Map);let g=typeof u=="string"?u:u.target;n.get(d).set(r,g);}for(let[r,o]of n)if(f[r]={},o.size===1){let d=[...o.entries()][0],u=d?d[1]:"unknown";c[r]=`(facts) => {
14
+ facts.state = '${u}';
15
+ }`;}else {let d=[...o.entries()].map(([u,g])=>` case '${u}': facts.state = '${g}'; break;`).join(`
16
+ `);c[r]=`(facts) => {
17
+ switch (facts.state) {
18
+ ${d}
19
+ }
20
+ }`;}let a=[` facts.state = '${e.initial}';`];if(e.context)for(let[r,o]of Object.entries(e.context))a.push(` facts.${r} = ${JSON.stringify(o)};`);let v=`(facts) => {
21
+ ${a.join(`
22
+ `)}
23
+ }`;return {name:e.id,facts:t,derivations:s,events:f,requirements:{},initCode:v,deriveCode:i,eventsCode:c}}function C(e){let t=["import { createModule, t } from '@directive-run/core';","",`const ${e.name}Module = createModule('${e.name}', {`," schema: {"," facts: {"];for(let[s,i]of Object.entries(e.facts))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" derivations: {");for(let[s,i]of Object.entries(e.derivations))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" events: {");for(let[s,i]of Object.entries(e.events)){let f=Object.entries(i).map(([c,n])=>`${c}: ${n}`).join(", ");t.push(` ${s}: { ${f} },`);}if(t.push(" },"),t.push(" requirements: {},"),t.push(" },"),t.push(` init: ${e.initCode},`),Object.keys(e.deriveCode).length>0){t.push(" derive: {");for(let[s,i]of Object.entries(e.deriveCode))t.push(` ${s}: ${i},`);t.push(" },");}t.push(" events: {");for(let[s,i]of Object.entries(e.eventsCode))t.push(` ${s}: ${i},`);return t.push(" },"),t.push("});"),t.push(""),t.push(`export { ${e.name}Module };`),t.join(`
24
+ `)}function p(e){if(e===null)return "t.any().nullable()";if(e===void 0)return "t.any().optional()";switch(typeof e){case "number":return "t.number()";case "string":return "t.string()";case "boolean":return "t.boolean()";case "object":return Array.isArray(e)?"t.array(t.any())":"t.object()";default:return "t.any()"}}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $(e){let t=["[ ] Install directive: pnpm add directive","[ ] Create module file(s) for your state","[ ] Define schema with facts, derivations, events","[ ] Implement init function for initial state","[ ] Implement event handlers","[ ] Update imports in consuming code","[ ] Test the new implementation","[ ] Remove old state management code"];return [...{redux:["[ ] Convert reducers to event handlers","[ ] Convert selectors to derivations","[ ] Convert thunks to constraints + resolvers","[ ] Update useSelector to useDerived","[ ] Update useDispatch to system.dispatch"],zustand:["[ ] Convert store state to facts","[ ] Convert store actions to events","[ ] Convert computed getters to derivations","[ ] Update useStore hooks to useDirective hooks"],xstate:["[ ] Convert machine states to a 'state' fact","[ ] Convert state checks to derivations (isActive, etc.)","[ ] Convert events to Directive events","[ ] Convert guards to constraint 'when' conditions","[ ] Convert services/actors to constraints + resolvers","[ ] Update useMachine to useDirective hooks"]}[e]??[],...t]}exports.analyzeReduxSlice=m;exports.analyzeXStateMachine=y;exports.analyzeZustandStore=h;exports.generateMigrationChecklist=$;exports.generateModuleCode=C;//# sourceMappingURL=migration.cjs.map
25
+ //# sourceMappingURL=migration.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/migration.ts"],"names":["analyzeReduxSlice","config","facts","events","eventsCode","key","value","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","s","derivations","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","eventName","target","targetState","transitions","firstEntry","toState","cases","from","to","initLines","generateModuleCode","structure","lines","type","schema","schemaStr","k","v","code","str","generateMigrationChecklist","source","common"],"mappings":"aAmEO,SAASA,CAAAA,CAAkBC,CAAAA,CAAoD,CACrF,IAAMC,CAAAA,CAAgC,EAAC,CACjCC,CAAAA,CAAiD,EAAC,CAClDC,CAAAA,CAAqC,EAAC,CAG5C,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQL,CAAAA,CAAO,YAAY,CAAA,CAC5DC,CAAAA,CAAMG,CAAG,CAAA,CAAIE,CAAAA,CAAgBD,CAAK,EAInC,IAAA,IAAWE,CAAAA,IAAe,MAAA,CAAO,IAAA,CAAKP,CAAAA,CAAO,QAAQ,CAAA,CAEjCO,CAAAA,CAAY,QAAA,CAAS,IAAI,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,KAAK,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,MAAM,CAAA,EAE1GL,CAAAA,CAAOK,CAAW,C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O,SAASC,EACfC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAAS,CACd,2CAAA,CACA,2CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,uCACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,2DACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgCD,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGC,CAAM,CAC/B","file":"migration.cjs","sourcesContent":["/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.any()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.any().nullable()\";\n\tif (value === undefined) return \"t.any().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.any())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.any()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n"]}
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Migration Utilities for Directive
3
+ *
4
+ * Helpers for migrating from Redux, Zustand, or XState to Directive.
5
+ * These utilities help you understand your existing state management
6
+ * and generate equivalent Directive module structures.
7
+ */
8
+ /** Redux slice configuration (simplified) */
9
+ interface ReduxSliceConfig {
10
+ name: string;
11
+ initialState: Record<string, unknown>;
12
+ reducers: Record<string, (state: unknown, action?: {
13
+ payload?: unknown;
14
+ }) => void>;
15
+ }
16
+ /** Zustand store configuration (simplified) */
17
+ interface ZustandStoreConfig {
18
+ state: Record<string, unknown>;
19
+ actions: Record<string, (...args: unknown[]) => void>;
20
+ }
21
+ /** XState machine configuration (simplified) */
22
+ interface XStateMachineConfig {
23
+ id: string;
24
+ initial: string;
25
+ states: Record<string, {
26
+ on?: Record<string, string | {
27
+ target: string;
28
+ }>;
29
+ }>;
30
+ context?: Record<string, unknown>;
31
+ }
32
+ /** Generated Directive module structure */
33
+ interface DirectiveModuleStructure {
34
+ name: string;
35
+ facts: Record<string, string>;
36
+ derivations: Record<string, string>;
37
+ events: Record<string, Record<string, string>>;
38
+ requirements: Record<string, unknown>;
39
+ initCode: string;
40
+ deriveCode: Record<string, string>;
41
+ eventsCode: Record<string, string>;
42
+ }
43
+ /**
44
+ * Analyze a Redux slice and generate a Directive module structure.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const reduxConfig = {
49
+ * name: 'counter',
50
+ * initialState: { value: 0, status: 'idle' },
51
+ * reducers: {
52
+ * increment: (state) => { state.value += 1; },
53
+ * decrement: (state) => { state.value -= 1; },
54
+ * },
55
+ * };
56
+ *
57
+ * const structure = analyzeReduxSlice(reduxConfig);
58
+ * console.log(generateModuleCode(structure));
59
+ * ```
60
+ */
61
+ declare function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure;
62
+ /**
63
+ * Analyze a Zustand store and generate a Directive module structure.
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * const zustandConfig = {
68
+ * state: { count: 0, loading: false },
69
+ * actions: {
70
+ * increment: () => {},
71
+ * decrement: () => {},
72
+ * setLoading: (loading: boolean) => {},
73
+ * },
74
+ * };
75
+ *
76
+ * const structure = analyzeZustandStore(zustandConfig);
77
+ * console.log(generateModuleCode(structure));
78
+ * ```
79
+ */
80
+ declare function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure;
81
+ /**
82
+ * Analyze an XState machine and generate a Directive module structure.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const xstateConfig = {
87
+ * id: 'toggle',
88
+ * initial: 'inactive',
89
+ * states: {
90
+ * inactive: { on: { TOGGLE: 'active' } },
91
+ * active: { on: { TOGGLE: 'inactive' } },
92
+ * },
93
+ * };
94
+ *
95
+ * const structure = analyzeXStateMachine(xstateConfig);
96
+ * console.log(generateModuleCode(structure));
97
+ * ```
98
+ */
99
+ declare function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure;
100
+ /**
101
+ * Generate Directive module code from a structure.
102
+ */
103
+ declare function generateModuleCode(structure: DirectiveModuleStructure): string;
104
+ /**
105
+ * Generate a migration checklist for a given state management pattern.
106
+ */
107
+ declare function generateMigrationChecklist(source: "redux" | "zustand" | "xstate"): string[];
108
+
109
+ export { type DirectiveModuleStructure, type ReduxSliceConfig, type XStateMachineConfig, type ZustandStoreConfig, analyzeReduxSlice, analyzeXStateMachine, analyzeZustandStore, generateMigrationChecklist, generateModuleCode };
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Migration Utilities for Directive
3
+ *
4
+ * Helpers for migrating from Redux, Zustand, or XState to Directive.
5
+ * These utilities help you understand your existing state management
6
+ * and generate equivalent Directive module structures.
7
+ */
8
+ /** Redux slice configuration (simplified) */
9
+ interface ReduxSliceConfig {
10
+ name: string;
11
+ initialState: Record<string, unknown>;
12
+ reducers: Record<string, (state: unknown, action?: {
13
+ payload?: unknown;
14
+ }) => void>;
15
+ }
16
+ /** Zustand store configuration (simplified) */
17
+ interface ZustandStoreConfig {
18
+ state: Record<string, unknown>;
19
+ actions: Record<string, (...args: unknown[]) => void>;
20
+ }
21
+ /** XState machine configuration (simplified) */
22
+ interface XStateMachineConfig {
23
+ id: string;
24
+ initial: string;
25
+ states: Record<string, {
26
+ on?: Record<string, string | {
27
+ target: string;
28
+ }>;
29
+ }>;
30
+ context?: Record<string, unknown>;
31
+ }
32
+ /** Generated Directive module structure */
33
+ interface DirectiveModuleStructure {
34
+ name: string;
35
+ facts: Record<string, string>;
36
+ derivations: Record<string, string>;
37
+ events: Record<string, Record<string, string>>;
38
+ requirements: Record<string, unknown>;
39
+ initCode: string;
40
+ deriveCode: Record<string, string>;
41
+ eventsCode: Record<string, string>;
42
+ }
43
+ /**
44
+ * Analyze a Redux slice and generate a Directive module structure.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const reduxConfig = {
49
+ * name: 'counter',
50
+ * initialState: { value: 0, status: 'idle' },
51
+ * reducers: {
52
+ * increment: (state) => { state.value += 1; },
53
+ * decrement: (state) => { state.value -= 1; },
54
+ * },
55
+ * };
56
+ *
57
+ * const structure = analyzeReduxSlice(reduxConfig);
58
+ * console.log(generateModuleCode(structure));
59
+ * ```
60
+ */
61
+ declare function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure;
62
+ /**
63
+ * Analyze a Zustand store and generate a Directive module structure.
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * const zustandConfig = {
68
+ * state: { count: 0, loading: false },
69
+ * actions: {
70
+ * increment: () => {},
71
+ * decrement: () => {},
72
+ * setLoading: (loading: boolean) => {},
73
+ * },
74
+ * };
75
+ *
76
+ * const structure = analyzeZustandStore(zustandConfig);
77
+ * console.log(generateModuleCode(structure));
78
+ * ```
79
+ */
80
+ declare function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure;
81
+ /**
82
+ * Analyze an XState machine and generate a Directive module structure.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const xstateConfig = {
87
+ * id: 'toggle',
88
+ * initial: 'inactive',
89
+ * states: {
90
+ * inactive: { on: { TOGGLE: 'active' } },
91
+ * active: { on: { TOGGLE: 'inactive' } },
92
+ * },
93
+ * };
94
+ *
95
+ * const structure = analyzeXStateMachine(xstateConfig);
96
+ * console.log(generateModuleCode(structure));
97
+ * ```
98
+ */
99
+ declare function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure;
100
+ /**
101
+ * Generate Directive module code from a structure.
102
+ */
103
+ declare function generateModuleCode(structure: DirectiveModuleStructure): string;
104
+ /**
105
+ * Generate a migration checklist for a given state management pattern.
106
+ */
107
+ declare function generateMigrationChecklist(source: "redux" | "zustand" | "xstate"): string[];
108
+
109
+ export { type DirectiveModuleStructure, type ReduxSliceConfig, type XStateMachineConfig, type ZustandStoreConfig, analyzeReduxSlice, analyzeXStateMachine, analyzeZustandStore, generateMigrationChecklist, generateModuleCode };
@@ -0,0 +1,25 @@
1
+ function m(e){let t={},s={},i={};for(let[n,a]of Object.entries(e.initialState))t[n]=p(a);for(let n of Object.keys(e.reducers))n.includes("By")||n.includes("Set")||n.includes("With")?(s[n]={payload:"t.any()"},i[n]=`(facts, { payload }) => {
2
+ // TODO: Implement ${n}
3
+ }`):(s[n]={},i[n]=`(facts) => {
4
+ // TODO: Implement ${n}
5
+ }`);let c=`(facts) => {
6
+ ${Object.entries(e.initialState).map(([n,a])=>` facts.${n} = ${JSON.stringify(a)};`).join(`
7
+ `)}
8
+ }`;return {name:e.name,facts:t,derivations:{},events:s,requirements:{},initCode:c,deriveCode:{},eventsCode:i}}function h(e){let t={},s={},i={};for(let[n,a]of Object.entries(e.state))t[n]=p(a);for(let n of Object.keys(e.actions))s[n]={},i[n]=`(facts) => {
9
+ // TODO: Implement ${n}
10
+ }`;let c=`(facts) => {
11
+ ${Object.entries(e.state).map(([n,a])=>` facts.${n} = ${JSON.stringify(a)};`).join(`
12
+ `)}
13
+ }`;return {name:"store",facts:t,derivations:{},events:s,requirements:{},initCode:c,deriveCode:{},eventsCode:i}}function y(e){let t={state:`t.string<${Object.keys(e.states).map(r=>`'${r}'`).join(" | ")}>()`},s={},i={},f={},c={};if(e.context)for(let[r,o]of Object.entries(e.context))t[r]=p(o);for(let r of Object.keys(e.states)){let o=`is${l(r)}`;s[o]="t.boolean()",i[o]=`(facts) => facts.state === '${r}'`;}let n=new Map;for(let[r,o]of Object.entries(e.states))if(o.on)for(let[d,u]of Object.entries(o.on)){n.has(d)||n.set(d,new Map);let g=typeof u=="string"?u:u.target;n.get(d).set(r,g);}for(let[r,o]of n)if(f[r]={},o.size===1){let d=[...o.entries()][0],u=d?d[1]:"unknown";c[r]=`(facts) => {
14
+ facts.state = '${u}';
15
+ }`;}else {let d=[...o.entries()].map(([u,g])=>` case '${u}': facts.state = '${g}'; break;`).join(`
16
+ `);c[r]=`(facts) => {
17
+ switch (facts.state) {
18
+ ${d}
19
+ }
20
+ }`;}let a=[` facts.state = '${e.initial}';`];if(e.context)for(let[r,o]of Object.entries(e.context))a.push(` facts.${r} = ${JSON.stringify(o)};`);let v=`(facts) => {
21
+ ${a.join(`
22
+ `)}
23
+ }`;return {name:e.id,facts:t,derivations:s,events:f,requirements:{},initCode:v,deriveCode:i,eventsCode:c}}function C(e){let t=["import { createModule, t } from '@directive-run/core';","",`const ${e.name}Module = createModule('${e.name}', {`," schema: {"," facts: {"];for(let[s,i]of Object.entries(e.facts))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" derivations: {");for(let[s,i]of Object.entries(e.derivations))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" events: {");for(let[s,i]of Object.entries(e.events)){let f=Object.entries(i).map(([c,n])=>`${c}: ${n}`).join(", ");t.push(` ${s}: { ${f} },`);}if(t.push(" },"),t.push(" requirements: {},"),t.push(" },"),t.push(` init: ${e.initCode},`),Object.keys(e.deriveCode).length>0){t.push(" derive: {");for(let[s,i]of Object.entries(e.deriveCode))t.push(` ${s}: ${i},`);t.push(" },");}t.push(" events: {");for(let[s,i]of Object.entries(e.eventsCode))t.push(` ${s}: ${i},`);return t.push(" },"),t.push("});"),t.push(""),t.push(`export { ${e.name}Module };`),t.join(`
24
+ `)}function p(e){if(e===null)return "t.any().nullable()";if(e===void 0)return "t.any().optional()";switch(typeof e){case "number":return "t.number()";case "string":return "t.string()";case "boolean":return "t.boolean()";case "object":return Array.isArray(e)?"t.array(t.any())":"t.object()";default:return "t.any()"}}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $(e){let t=["[ ] Install directive: pnpm add directive","[ ] Create module file(s) for your state","[ ] Define schema with facts, derivations, events","[ ] Implement init function for initial state","[ ] Implement event handlers","[ ] Update imports in consuming code","[ ] Test the new implementation","[ ] Remove old state management code"];return [...{redux:["[ ] Convert reducers to event handlers","[ ] Convert selectors to derivations","[ ] Convert thunks to constraints + resolvers","[ ] Update useSelector to useDerived","[ ] Update useDispatch to system.dispatch"],zustand:["[ ] Convert store state to facts","[ ] Convert store actions to events","[ ] Convert computed getters to derivations","[ ] Update useStore hooks to useDirective hooks"],xstate:["[ ] Convert machine states to a 'state' fact","[ ] Convert state checks to derivations (isActive, etc.)","[ ] Convert events to Directive events","[ ] Convert guards to constraint 'when' conditions","[ ] Convert services/actors to constraints + resolvers","[ ] Update useMachine to useDirective hooks"]}[e]??[],...t]}export{m as analyzeReduxSlice,y as analyzeXStateMachine,h as analyzeZustandStore,$ as generateMigrationChecklist,C as generateModuleCode};//# sourceMappingURL=migration.js.map
25
+ //# sourceMappingURL=migration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/migration.ts"],"names":["analyzeReduxSlice","config","facts","events","eventsCode","key","value","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","s","derivations","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","eventName","target","targetState","transitions","firstEntry","toState","cases","from","to","initLines","generateModuleCode","structure","lines","type","schema","schemaStr","k","v","code","str","generateMigrationChecklist","source","common"],"mappings":"AAmEO,SAASA,CAAAA,CAAkBC,CAAAA,CAAoD,CACrF,IAAMC,CAAAA,CAAgC,EAAC,CACjCC,CAAAA,CAAiD,EAAC,CAClDC,CAAAA,CAAqC,EAAC,CAG5C,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQL,CAAAA,CAAO,YAAY,CAAA,CAC5DC,CAAAA,CAAMG,CAAG,CAAA,CAAIE,CAAAA,CAAgBD,CAAK,EAInC,IAAA,IAAWE,CAAAA,IAAe,MAAA,CAAO,IAAA,CAAKP,CAAAA,CAAO,QAAQ,CAAA,CAEjCO,CAAAA,CAAY,QAAA,CAAS,IAAI,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,KAAK,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,MAAM,CAAA,EAE1GL,CAAAA,CAAOK,CAAW,CAAA,CAAI,CAAE,OAAA,CAAS,SAAU,CAAA,CAC3CJ,CAAAA,CAAWI,CAAW,CAAA,CAAI,CAAA;AAAA,uBAAA,EAAqDA,CAAW;AAAA,GAAA,CAAA,GAE1FL,EAAOK,CAAW,CAAA,CAAI,EAAC,CACvBJ,CAAAA,CAAWI,CAAW,CAAA,CAAI,CAAA;AAAA,uBAAA,EAAwCA,CAAW;AAAA,GAAA,CAAA,CAAA,CAQ/E,IAAMC,CAAAA,CAAW,CAAA;AAAA,EAHC,MAAA,CAAO,QAAQR,CAAAA,CAAO,YAAY,EAClD,GAAA,CAAI,CAAC,CAACI,CAAAA,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,6CACD,CACD,CAAA,CAEgCD,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGC,CAAM,CAC/B","file":"migration.js","sourcesContent":["/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.any()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.any().nullable()\";\n\tif (value === undefined) return \"t.any().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.any())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.any()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n"]}
@@ -0,0 +1,3 @@
1
+ 'use strict';var U={debug:0,info:1,warn:2,error:3};function W(s={}){let{level:l="info",filter:a=()=>true,logger:o=console,prefix:c="[Directive]"}=s,i=U[l],t=(e,r,...f)=>{U[e]<i||a(r)&&o[e](`${c} ${r}`,...f);};return {name:"logging",onInit:()=>t("debug","init"),onStart:()=>t("info","start"),onStop:()=>t("info","stop"),onDestroy:()=>t("debug","destroy"),onFactSet:(e,r,f)=>{t("debug","fact.set",{key:e,value:r,prev:f});},onFactDelete:(e,r)=>{t("debug","fact.delete",{key:e,prev:r});},onFactsBatch:e=>{t("debug","facts.batch",{count:e.length,changes:e});},onDerivationCompute:(e,r,f)=>{t("debug","derivation.compute",{id:e,value:r,deps:f});},onDerivationInvalidate:e=>{t("debug","derivation.invalidate",{id:e});},onReconcileStart:()=>{t("debug","reconcile.start");},onReconcileEnd:e=>{t("debug","reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length,completed:e.completed.length,canceled:e.canceled.length});},onConstraintEvaluate:(e,r)=>{t("debug","constraint.evaluate",{id:e,active:r});},onConstraintError:(e,r)=>{t("error","constraint.error",{id:e,error:r});},onRequirementCreated:e=>{t("debug","requirement.created",{id:e.id,type:e.requirement.type});},onRequirementMet:(e,r)=>{t("info","requirement.met",{id:e.id,byResolver:r});},onRequirementCanceled:e=>{t("debug","requirement.canceled",{id:e.id});},onResolverStart:(e,r)=>{t("debug","resolver.start",{resolver:e,requirementId:r.id});},onResolverComplete:(e,r,f)=>{t("info","resolver.complete",{resolver:e,requirementId:r.id,duration:f});},onResolverError:(e,r,f)=>{t("error","resolver.error",{resolver:e,requirementId:r.id,error:f});},onResolverRetry:(e,r,f)=>{t("warn","resolver.retry",{resolver:e,requirementId:r.id,attempt:f});},onResolverCancel:(e,r)=>{t("debug","resolver.cancel",{resolver:e,requirementId:r.id});},onEffectRun:e=>{t("debug","effect.run",{id:e});},onEffectError:(e,r)=>{t("error","effect.error",{id:e,error:r});},onSnapshot:e=>{t("debug","timetravel.snapshot",{id:e.id,trigger:e.trigger});},onTimeTravel:(e,r)=>{t("info","timetravel.jump",{from:e,to:r});},onError:e=>{t("error","error",{source:e.source,sourceId:e.sourceId,message:e.message});},onErrorRecovery:(e,r)=>{t("warn","error.recovery",{source:e.source,sourceId:e.sourceId,strategy:r});}}}function J(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[]};if(!window.__DIRECTIVE__){let s=new Map;window.__DIRECTIVE__={systems:s,getSystem(l){return l?s.get(l)?.system??null:s.values().next().value?.system??null},getSystems(){return [...s.keys()]},inspect(l){return this.getSystem(l)?.inspect()??null},getEvents(l){return l?s.get(l)?.events??[]:s.values().next().value?.events??[]}};}return window.__DIRECTIVE__}function G(s={}){let{name:l="default",trace:a=false}=s,o=J(),c={system:null,events:[],maxEvents:1e3};o.systems.set(l,c);let i=(t,e)=>{a&&(c.events.push({timestamp:Date.now(),type:t,data:e}),c.events.length>c.maxEvents&&c.events.shift());};return {name:"devtools",onInit:t=>{c.system=t,i("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${l}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit");},onStart:()=>i("start",{}),onStop:()=>i("stop",{}),onDestroy:()=>{i("destroy",{}),o.systems.delete(l);},onFactSet:(t,e,r)=>{i("fact.set",{key:t,value:e,prev:r});},onFactsBatch:t=>{i("facts.batch",{changes:t});},onReconcileStart:()=>{i("reconcile.start",{});},onReconcileEnd:t=>{i("reconcile.end",t);},onConstraintEvaluate:(t,e)=>{i("constraint.evaluate",{id:t,active:e});},onRequirementCreated:t=>{i("requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,e)=>{i("requirement.met",{id:t.id,byResolver:e});},onResolverStart:(t,e)=>{i("resolver.start",{resolver:t,requirementId:e.id});},onResolverComplete:(t,e,r)=>{i("resolver.complete",{resolver:t,requirementId:e.id,duration:r});},onResolverError:(t,e,r)=>{i("resolver.error",{resolver:t,requirementId:e.id,error:String(r)});},onSnapshot:t=>{i("timetravel.snapshot",{id:t.id,trigger:t.trigger});},onTimeTravel:(t,e)=>{i("timetravel.jump",{from:t,to:e});},onError:t=>{i("error",{source:t.source,sourceId:t.sourceId,message:t.message});}}}function j(s,l=50){let a=new Set(["__proto__","constructor","prototype"]),o=new WeakSet;function c(i,t){if(t>l)return false;if(i==null||typeof i!="object")return true;let e=i;if(o.has(e))return true;if(o.add(e),Array.isArray(e)){for(let r of e)if(!c(r,t+1))return o.delete(e),false;return o.delete(e),true}for(let r of Object.keys(e))if(a.has(r)||!c(e[r],t+1))return o.delete(e),false;return o.delete(e),true}return c(s,0)}function z(s){let{storage:l,key:a,include:o,exclude:c=[],debounce:i=100,onRestore:t,onSave:e,onError:r}=s,f=null,b=null,y=new Set,T=n=>c.includes(n)?false:o?o.includes(n):true,E=()=>{try{let n=l.getItem(a);if(!n)return null;let g=JSON.parse(n);return typeof g!="object"||g===null?null:j(g)?g:(r?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(n){return r?.(n instanceof Error?n:new Error(String(n))),null}},D=()=>{if(b)try{let n={};for(let g of y)T(g)&&(n[g]=b.facts[g]);l.setItem(a,JSON.stringify(n)),e?.(n);}catch(n){r?.(n instanceof Error?n:new Error(String(n)));}},S=()=>{f&&clearTimeout(f),f=setTimeout(D,i);};return {name:"persistence",onInit:n=>{b=n;let g=E();g&&(b.facts.$store.batch(()=>{for(let[v,p]of Object.entries(g))T(v)&&(b.facts[v]=p,y.add(v));}),t?.(g));},onDestroy:()=>{f&&clearTimeout(f),D();},onFactSet:n=>{y.add(n),T(n)&&S();},onFactDelete:n=>{y.delete(n),T(n)&&S();},onFactsBatch:n=>{let g=false;for(let v of n)v.type==="set"?y.add(v.key):y.delete(v.key),T(v.key)&&(g=true);g&&S();}}}function K(s={}){let{onSlowConstraint:l,onSlowResolver:a,slowConstraintThresholdMs:o=16,slowResolverThresholdMs:c=1e3}=s,i=new Map,t=new Map,e=new Map,r={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},f=0,b=0,y=0;function T(n){let g=i.get(n);return g||(g={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},i.set(n,g)),g}function E(n){let g=t.get(n);return g||(g={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},t.set(n,g)),g}function D(n){let g=e.get(n);return g||(g={runs:0,errors:0,lastRunAt:0},e.set(n,g)),g}return {name:"performance",onStart(){f=Date.now();},onConstraintEvaluate(n,g){let v=performance.now(),p=T(n);if(p.evaluations++,p.lastEvaluatedAt=Date.now(),y>0){let h=v-y;p.totalDurationMs+=h;let A=p.evaluations;p.avgDurationMs=p.totalDurationMs/A,h>p.maxDurationMs&&(p.maxDurationMs=h),h>o&&l?.(n,h);}y=v;},onResolverStart(n,g){let v=E(n);v.starts++;},onResolverComplete(n,g,v){let p=E(n);p.completions++,p.totalDurationMs+=v,p.avgDurationMs=p.totalDurationMs/p.completions,v>p.maxDurationMs&&(p.maxDurationMs=v),p.lastCompletedAt=Date.now(),v>c&&a?.(n,v);},onResolverError(n,g,v){E(n).errors++;},onResolverRetry(n,g,v){E(n).retries++;},onResolverCancel(n,g){E(n).cancellations++;},onEffectRun(n){let g=D(n);g.runs++,g.lastRunAt=Date.now();},onEffectError(n,g){D(n).errors++;},onReconcileStart(){b=performance.now(),y=0;},onReconcileEnd(){let n=performance.now()-b;r.runs++,r.totalDurationMs+=n,r.avgDurationMs=r.totalDurationMs/r.runs,n>r.maxDurationMs&&(r.maxDurationMs=n);},getSnapshot(){let n={};for(let[p,h]of i)n[p]={...h};let g={};for(let[p,h]of t)g[p]={...h};let v={};for(let[p,h]of e)v[p]={...h};return {constraints:n,resolvers:g,effects:v,reconcile:{...r},uptime:f?Date.now()-f:0}},reset(){i.clear(),t.clear(),e.clear(),r.runs=0,r.totalDurationMs=0,r.avgDurationMs=0,r.maxDurationMs=0,y=0;}}}function F(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function H(s,l){if(s.length===0)return 0;let a=[...s].sort((c,i)=>c-i),o=Math.ceil(l/100*a.length)-1;return a[Math.max(0,o)]??0}function Q(s={}){let{serviceName:l="directive-agents",metrics:a={},tracing:o={},alerts:c=[],summaryMetrics:i={},events:t={}}=s,e={requests:i.requests??"agent.requests",errors:i.errors??"agent.errors",latency:i.latency??"agent.latency",tokens:i.tokens??"agent.tokens",cost:i.cost??"agent.cost"},{enabled:r=true,exportInterval:f,exporter:b,maxDataPoints:y=1e3}=a,{enabled:T=true,sampleRate:E=1,maxSpans:D=1e3,exporter:S}=o,n=Date.now(),g=new Map,v=new Map,p=[],h=[],A=new Map,w=new Map,_;f&&(b||S)&&(_=setInterval(async()=>{try{if(b&&r&&await b(Array.from(w.values())),S&&T){let u=p.splice(0,100);u.length>0&&await S(u);}}catch(u){console.error("[Directive Observability] Export error:",u);}},f));function L(u){if(!r)return;let d=`${u.name}:${JSON.stringify(Object.fromEntries(Object.entries(u.labels).sort()))}`,m=g.get(d);m||(m=[],g.set(d,m)),m.push(u),m.length>y&&m.shift(),B(u.name,m),t.onMetricRecorded?.(u),M(u.name);}function B(u,d){if(d.length===0)return;let m=d.map(C=>C.value),x=m.reduce((C,R)=>C+R,0),P=d[0],O=m[m.length-1],I={name:u,type:P.type,count:d.length,sum:x,min:Math.min(...m),max:Math.max(...m),avg:x/d.length,lastValue:O,lastUpdated:Date.now()};w.set(u,I);}function M(u){for(let d of c){if(d.metric!==u)continue;let m=w.get(u);if(!m)continue;let x=`${d.metric}:${d.threshold}`,P=A.get(x),O=d.cooldownMs??6e4;if(P&&Date.now()-P<O)continue;let I=d.operator??">",C=m.lastValue,R=d.threshold,N=false;switch(I){case ">":N=C>R;break;case "<":N=C<R;break;case ">=":N=C>=R;break;case "<=":N=C<=R;break;case "==":N=C===R;break}if(N){let V={alertId:F(),metric:u,currentValue:C,threshold:R,operator:I,action:d.action,timestamp:Date.now(),message:`Alert: ${u} ${I} ${R} (current: ${C})`};switch(h.push(V),h.length>1e3&&h.splice(0,h.length-1e3),A.set(x,Date.now()),t.onAlert?.(V),d.action){case "log":console.log(`[Observability] ${V.message}`);break;case "warn":console.warn(`[Observability] ${V.message}`);break;case "alert":console.error(`[Observability ALERT] ${V.message}`);break;case "callback":d.callback?.(m,R);break}}}}function k(u){let d=[];for(let[m,x]of g)if(m.startsWith(`${u}:`))for(let P of x)d.push(P.value);return d.length===0?{}:{p50:H(d,50),p90:H(d,90),p99:H(d,99)}}return {incrementCounter(u,d={},m=1){L({name:u,type:"counter",value:m,labels:d,timestamp:Date.now()});},setGauge(u,d,m={}){L({name:u,type:"gauge",value:d,labels:m,timestamp:Date.now()});},observeHistogram(u,d,m={}){L({name:u,type:"histogram",value:d,labels:m,timestamp:Date.now()});},startSpan(u,d){if(Math.random()>E)return {traceId:"sampled-out",spanId:"sampled-out",operationName:u,serviceName:l,startTime:Date.now(),status:"ok",tags:{},logs:[]};let m={traceId:d?v.get(d)?.traceId??F():F(),spanId:F(),parentSpanId:d,operationName:u,serviceName:l,startTime:Date.now(),status:"ok",tags:{},logs:[]};return T&&(v.set(m.spanId,m),t.onSpanStart?.(m)),m},endSpan(u,d="ok"){if(u==="sampled-out")return;let m=v.get(u);if(m){for(m.endTime=Date.now(),m.duration=m.endTime-m.startTime,m.status=d,v.delete(u),p.push(m);p.length>D;)p.shift();L({name:`${m.operationName}.latency`,type:"histogram",value:m.duration,labels:{},timestamp:Date.now()}),d==="error"&&L({name:`${m.operationName}.errors`,type:"counter",value:1,labels:{},timestamp:Date.now()}),t.onSpanEnd?.(m);}},addSpanLog(u,d,m="info"){if(u==="sampled-out")return;let x=v.get(u);x&&x.logs.push({timestamp:Date.now(),message:d,level:m});},addSpanTag(u,d,m){if(u==="sampled-out")return;let x=v.get(u);x&&(x.tags[d]=m);},getDashboard(){let u=w.get(e.requests),d=w.get(e.errors),m=w.get(e.latency),x=w.get(e.tokens),P=w.get(e.cost),O=u?.sum??0,I=d?.sum??0,C=O>0?I/O:0,R=m?k(e.latency):{};return {service:{name:l,uptime:Date.now()-n,startTime:n},metrics:Object.fromEntries(w),traces:[...p].slice(-100),alerts:[...h].slice(-50),summary:{totalRequests:O,totalErrors:I,errorRate:C,avgLatency:m?.avg??0,p99Latency:R.p99??0,activeSpans:v.size,totalTokens:x?.sum??0,totalCost:P?.sum??0}}},getMetric(u){let d=w.get(u);if(!d)return;let m=k(u);return {...d,...m}},getTraces(u=100){return [...p].slice(-u)},getAlerts(){return [...h]},export(){return {metrics:Array.from(w.values()),traces:[...p],alerts:[...h]}},clear(){g.clear(),w.clear(),v.clear(),p.length=0,h.length=0,A.clear();},async dispose(){_&&(clearInterval(_),_=void 0);try{b&&r&&w.size>0&&await b(Array.from(w.values())),S&&T&&p.length>0&&await S([...p]);}catch(u){console.error("[Directive Observability] Error flushing data during dispose:",u);}g.clear(),w.clear(),v.clear(),p.length=0,h.length=0,A.clear();},getHealthStatus(){let u=w.get(e.requests),d=w.get(e.errors),m=u?.sum??0,x=d?.sum??0,P=m>0?x/m:0,O=h.filter(I=>Date.now()-I.timestamp<3e5).length;return {healthy:P<.1&&O===0,uptime:Date.now()-n,errorRate:P,activeAlerts:O}}}}function X(s){return {trackRun(l,a){let o={agent:l};s.incrementCounter("agent.requests",o),a.success||s.incrementCounter("agent.errors",o),s.observeHistogram("agent.latency",a.latencyMs,o),a.inputTokens!==void 0&&(s.incrementCounter("agent.tokens.input",o,a.inputTokens),s.incrementCounter("agent.tokens",o,a.inputTokens)),a.outputTokens!==void 0&&(s.incrementCounter("agent.tokens.output",o,a.outputTokens),s.incrementCounter("agent.tokens",o,a.outputTokens)),a.cost!==void 0&&s.incrementCounter("agent.cost",o,a.cost),a.toolCalls!==void 0&&s.incrementCounter("agent.tool_calls",o,a.toolCalls);},trackGuardrail(l,a){let o={guardrail:l};s.incrementCounter("guardrail.checks",o),a.passed||s.incrementCounter("guardrail.failures",o),a.blocked&&s.incrementCounter("guardrail.blocks",o),s.observeHistogram("guardrail.latency",a.latencyMs,o);},trackApproval(l,a){let o={tool:l};s.incrementCounter("approval.requests",o),a.approved?s.incrementCounter("approval.approved",o):s.incrementCounter("approval.rejected",o),a.timedOut&&s.incrementCounter("approval.timeouts",o),s.observeHistogram("approval.wait_time",a.waitTimeMs,o);},trackHandoff(l,a,o){s.incrementCounter("handoff.count",{from:l,to:a}),s.observeHistogram("handoff.latency",o);}}}function Y(s){let l=[{key:"service.name",value:{stringValue:s.serviceName??"directive-agents"}}];if(s.serviceVersion&&l.push({key:"service.version",value:{stringValue:s.serviceVersion}}),s.resourceAttributes)for(let[a,o]of Object.entries(s.resourceAttributes))l.push({key:a,value:{stringValue:o}});return {attributes:l}}function $(s){return `${BigInt(s)*BigInt(1e6)}`}function Z(s){switch(s){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function ee(s,l,a){let o=s.map(c=>{let i=c.lastUpdated-6e4,t=[{asInt:c.type==="counter"?c.sum:void 0,asDouble:c.type!=="counter"?c.lastValue:void 0,timeUnixNano:$(c.lastUpdated),startTimeUnixNano:$(i),attributes:[]}],e=Z(c.type),r={name:c.name,unit:""};return e==="sum"?r.sum={dataPoints:t,aggregationTemporality:2,isMonotonic:true}:e==="histogram"?r.histogram={dataPoints:[{count:c.count,sum:c.sum,min:c.min,max:c.max,timeUnixNano:$(c.lastUpdated),startTimeUnixNano:$(i),attributes:[]}],aggregationTemporality:2}:r.gauge={dataPoints:t},r});return {resourceMetrics:[{resource:l,scopeMetrics:[{scope:{name:"directive",version:a},metrics:o}]}]}}function te(s,l,a){let o=s.map(c=>{let i=c.logs.map(r=>({timeUnixNano:$(r.timestamp),name:r.level,attributes:[{key:"message",value:{stringValue:r.message}},{key:"level",value:{stringValue:r.level}}]})),t=Object.entries(c.tags).map(([r,f])=>({key:r,value:typeof f=="string"?{stringValue:f}:typeof f=="number"?{intValue:`${f}`}:{boolValue:f}})),e=c.status==="ok"?1:c.status==="error"?2:0;return {traceId:c.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:c.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:c.parentSpanId?c.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:c.operationName,kind:1,startTimeUnixNano:$(c.startTime),endTimeUnixNano:c.endTime?$(c.endTime):$(c.startTime),attributes:t,events:i,status:{code:e}}});return {resourceSpans:[{resource:l,scopeSpans:[{scope:{name:"directive",version:a},spans:o}]}]}}function re(s){let{endpoint:l,headers:a={},scopeVersion:o="0.1.0",timeoutMs:c=1e4,fetch:i=globalThis.fetch,onError:t}=s;try{let f=new URL(l);if(f.protocol!=="http:"&&f.protocol!=="https:")throw new Error("Only http: and https: protocols are supported")}catch(f){throw new Error(`[Directive OTLP] Invalid endpoint URL "${l}": ${f instanceof Error?f.message:String(f)}`)}if(/\/v1\/(metrics|traces)/.test(l)&&console.warn(`[Directive OTLP] Endpoint "${l}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),c<=0||!Number.isFinite(c))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${c}`);let e=Y(s);async function r(f,b,y){let T=`${l.replace(/\/$/,"")}${f}`,E=new AbortController,D=setTimeout(()=>E.abort(),c);try{let S=await i(T,{method:"POST",headers:{"Content-Type":"application/json",...a},body:JSON.stringify(b),signal:E.signal});if(!S.ok)throw new Error(`OTLP export failed: ${S.status} ${S.statusText}`)}catch(S){let n=S instanceof Error?S:new Error(String(S));t?t(n,y):console.error(`[Directive OTLP] Export ${y} error:`,n.message);}finally{clearTimeout(D);}}return {async exportMetrics(f){if(f.length===0)return;let b=ee(f,e,o);await r("/v1/metrics",b,"metrics");},async exportTraces(f){if(f.length===0)return;let b=te(f,e,o);await r("/v1/traces",b,"traces");}}}var q=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(l,a,o="OPEN",c){let i=c?`[Directive CircuitBreaker] Circuit "${l}" is ${o}. ${c}`:`[Directive CircuitBreaker] Circuit "${l}" is ${o}. Request rejected. Try again in ${Math.ceil(a/1e3)}s.`;super(i),this.name="CircuitBreakerOpenError",this.retryAfterMs=a,this.state=o;}};function ne(s={}){let{failureThreshold:l=5,recoveryTimeMs:a=3e4,halfOpenMaxRequests:o=3,failureWindowMs:c=6e4,observability:i,metricPrefix:t="circuit_breaker",name:e="default",isFailure:r=()=>true,onStateChange:f}=s;if(l<1||!Number.isFinite(l))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${l}`);if(a<=0||!Number.isFinite(a))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${a}`);if(o<1||!Number.isFinite(o))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${o}`);if(c<=0||!Number.isFinite(c))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${c}`);let b="CLOSED",y=[],T=0,E=0,D=Date.now(),S=0,n=0,g=0,v=0,p=0,h=null,A=null;function w(M){if(b===M)return;let k=b;b=M,D=Date.now(),M==="OPEN"&&(S=Date.now()),M==="HALF_OPEN"&&(T=0,E=0),f?.(k,M),i&&i.incrementCounter(`${t}.state_change`,{name:e,from:k,to:M});}function _(){let M=Date.now()-c;return y=y.filter(k=>k>M),y.length}function L(){v++,A=Date.now(),i&&i.incrementCounter(`${t}.success`,{name:e}),b==="HALF_OPEN"&&(E++,E>=o&&(w("CLOSED"),y=[]));}function B(M){if(!r(M)){L();return}g++,h=Date.now(),y.push(Date.now());let k=l*2;if(y.length>k&&(y=y.slice(-k)),i&&i.incrementCounter(`${t}.failure`,{name:e}),b==="HALF_OPEN"){w("OPEN");return}b==="CLOSED"&&_()>=l&&w("OPEN");}return {async execute(M){if(n++,i&&i.incrementCounter(`${t}.requests`,{name:e}),b==="OPEN")if(Date.now()-S>=a)w("HALF_OPEN");else throw p++,i&&i.incrementCounter(`${t}.rejected`,{name:e}),new q(e,a-(Date.now()-S));if(b==="HALF_OPEN"){if(T>=o)throw p++,new q(e,a,"HALF_OPEN",`Max trial requests (${o}) reached.`);T++;}let k=Date.now();try{let u=await M();return L(),i&&i.observeHistogram(`${t}.latency`,Date.now()-k,{name:e}),u}catch(u){let d=u instanceof Error?u:new Error(String(u));throw B(d),i&&i.observeHistogram(`${t}.latency`,Date.now()-k,{name:e}),u}},getState(){return b==="OPEN"&&Date.now()-S>=a&&w("HALF_OPEN"),b},getStats(){return {state:this.getState(),totalRequests:n,totalFailures:g,totalSuccesses:v,totalRejected:p,recentFailures:_(),lastFailureTime:h,lastSuccessTime:A,lastStateChange:D}},forceState(M){w(M);},reset(){let M=b;b="CLOSED",y=[],T=0,E=0,D=Date.now(),S=0,n=0,g=0,v=0,p=0,h=null,A=null,M!=="CLOSED"&&f?.(M,"CLOSED");},isAllowed(){return b==="CLOSED"?true:b==="OPEN"?Date.now()-S>=a:T<o}}}
2
+ exports.CircuitBreakerOpenError=q;exports.createAgentMetrics=X;exports.createCircuitBreaker=ne;exports.createOTLPExporter=re;exports.createObservability=Q;exports.devtoolsPlugin=G;exports.loggingPlugin=W;exports.performancePlugin=K;exports.persistencePlugin=z;//# sourceMappingURL=index.cjs.map
3
+ //# sourceMappingURL=index.cjs.map