@private.me/xbind 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/README.md +55 -7
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.d.ts +84 -0
  174. package/dist-standalone/plugins/logging.js +163 -0
  175. package/dist-standalone/plugins/metrics.d.ts +111 -0
  176. package/dist-standalone/plugins/metrics.js +176 -0
  177. package/dist-standalone/plugins/validation.d.ts +104 -0
  178. package/dist-standalone/plugins/validation.js +297 -0
  179. package/dist-standalone/policy.js +315 -1
  180. package/dist-standalone/progress-callbacks.js +576 -1
  181. package/dist-standalone/redis-nonce-store.js +72 -1
  182. package/dist-standalone/registry-middleware.js +47 -1
  183. package/dist-standalone/retry-strategies.js +534 -1
  184. package/dist-standalone/retry-transport.js +98 -1
  185. package/dist-standalone/runtime/browser.d.ts +311 -0
  186. package/dist-standalone/runtime/browser.js +516 -0
  187. package/dist-standalone/runtime/edge.d.ts +282 -0
  188. package/dist-standalone/runtime/edge.js +511 -0
  189. package/dist-standalone/runtime/react-native.d.ts +157 -0
  190. package/dist-standalone/runtime/react-native.js +383 -0
  191. package/dist-standalone/security-policy.js +239 -1
  192. package/dist-standalone/serialization.js +1031 -1
  193. package/dist-standalone/split-channel.js +219 -1
  194. package/dist-standalone/subscription-proof.js +224 -1
  195. package/dist-standalone/succession.js +142 -1
  196. package/dist-standalone/timeouts.js +398 -1
  197. package/dist-standalone/trace-context.js +414 -1
  198. package/dist-standalone/trace-spans.js +488 -1
  199. package/dist-standalone/transport.js +59 -1
  200. package/dist-standalone/trust-registry.js +950 -1
  201. package/dist-standalone/types/error-response.d.ts +209 -0
  202. package/dist-standalone/types/error-response.js +52 -0
  203. package/dist-standalone/vault-auth.js +174 -1
  204. package/dist-standalone/vault-store-loader.js +187 -1
  205. package/dist-standalone/verify.js +16 -1
  206. package/dist-standalone/version-info.js +530 -1
  207. package/dist-standalone/xfetch.js +335 -1
  208. package/package.json +4 -10
  209. package/share1.dat +0 -0
  210. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  211. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  212. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  213. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  214. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  215. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  216. package/dist-standalone/cjs/package.json +0 -3
  217. package/dist-standalone/package.json +0 -10
@@ -1,2 +1,493 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(null!=t)for(var r=e(t),i=0;i<r.length;i++)"default"!==r[i]&&__createBinding(n,t,r[i]);return __setModuleDefault(n,t),n}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.initCommand=initCommand,exports.main=main;const node_util_1=require("node:util"),fs=__importStar(require("node:fs")),path=__importStar(require("node:path")),node_child_process_1=require("node:child_process"),readline=__importStar(require("node:readline/promises")),node_process_1=require("node:process"),invite_js_1=require("../invite.js");function getTemplateDir(){let e=__dirname;for(;"/"!==e;){if(fs.existsSync(path.join(e,"package.json")))return path.join(e,"templates");e=path.dirname(e)}return path.join(__dirname,"../../templates")}const TEMPLATES={"node-typescript":{name:"Node.js + TypeScript",description:"Node.js with TypeScript, best for backend services",packageManager:"npm",entryPoint:"src/index.ts",startCommand:"npm run dev"},"node-javascript":{name:"Node.js + JavaScript",description:"Node.js with JavaScript, minimal setup",packageManager:"npm",entryPoint:"src/index.js",startCommand:"npm start"},deno:{name:"Deno",description:"Modern TypeScript runtime",packageManager:"deno",entryPoint:"mod.ts",startCommand:"deno run --allow-net --allow-env --allow-read mod.ts"},"cloudflare-worker":{name:"Cloudflare Worker",description:"Edge runtime on Cloudflare",packageManager:"npm",entryPoint:"src/index.ts",startCommand:"npm run dev"},"vercel-function":{name:"Vercel Function",description:"Serverless function on Vercel",packageManager:"npm",entryPoint:"api/xbind.ts",startCommand:"npm run dev"}};class Spinner{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];currentFrame=0;intervalId;message;constructor(e){this.message=e}start(){this.intervalId=setInterval(()=>{const e=this.frames[this.currentFrame];process.stdout.write(`\r${e} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(e){this.stop(),process.stdout.write(`\r✅ ${e??this.message}\n`)}fail(e){this.stop(),process.stdout.write(`\r❌ ${e??this.message}\n`)}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}}function normalizeInviteUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:(e.startsWith("XBD-"),`${t}/invite/${e}`)}function isValidProjectName(e){return/^[a-z0-9-_]+$/i.test(e)&&e.length>0&&e.length<=100}async function prompt(e,t){const n=readline.createInterface({input:node_process_1.stdin,output:node_process_1.stdout}),r=await n.question(t?`${e} (${t}): `:`${e}: `);return n.close(),r.trim()||t||""}async function select(e,t,n=0){console.log(e),t.forEach((e,t)=>{const r=t===n?"→":" ";console.log(` ${r} ${t+1}. ${e.label} - ${e.description}`)});const r=readline.createInterface({input:node_process_1.stdin,output:node_process_1.stdout}),i=await r.question(`Select (1-${t.length}): `);r.close();const o=parseInt(i.trim(),10)-1;return o>=0&&o<t.length?t[o]?.value??t[n]?.value??"":t[n]?.value??""}function runCommand(e,t,n){return new Promise((r,i)=>{const o=(0,node_child_process_1.spawn)(e,t,{cwd:n,stdio:"ignore",shell:!0});o.on("close",e=>{0===e?r():i(new Error(`Command failed with code ${e??"unknown"}`))}),o.on("error",i)})}async function copyTemplate(e,t,n){const r=path.join(getTemplateDir(),e),i=await fs.promises.readdir(r,{recursive:!0,withFileTypes:!0});for(const e of i)if(e.isFile()){const i=e.parentPath||e.path||r,o=path.relative(r,path.join(i,e.name)),s=path.join(r,o),a=path.join(t,o);await fs.promises.mkdir(path.dirname(a),{recursive:!0});let c=await fs.promises.readFile(s,"utf-8");n&&(c=c.replace(/{{INVITE_URL}}/g,n.url),c=c.replace(/{{INVITE_ID}}/g,n.id),c=c.replace(/{{SERVICE_NAME}}/g,n.from.name),c=c.replace(/{{SERVICE_DID}}/g,n.from.did),c=c.replace(/{{SERVICE_ENDPOINT}}/g,n.from.endpoint)),await fs.promises.writeFile(a,c,"utf-8")}}async function installDependencies(e,t){"npm"===t&&await runCommand("npm",["install"],e)}async function initCommand(e={}){const t=e.registryUrl||"https://xbind.to";let n,r;if(e.invite){r=normalizeInviteUrl(e.invite,t);const i=new Spinner("Fetching invite details...");i.start();try{const e=new invite_js_1.InviteService({inviteApiUrl:t}),o=await e.get(r);if(!o.ok)return i.fail(`Failed to fetch invite: ${o.error.message}`),o.error.hint&&console.error(`Hint: ${o.error.hint}`),void(process.exitCode=1);if(n=o.value,!n)return i.fail("Invalid invite data received"),void(process.exitCode=1);i.succeed(`Connected to ${n.from.name}`)}catch(e){return i.fail("Failed to fetch invite details"),console.error(e instanceof Error?e.message:String(e)),void(process.exitCode=1)}}let i=e.name,o=e.runtime;if(e.yes)i=i||"my-xbind-app",o=o||"node-typescript";else{if(!i){const e=n?`connect-${n.from.name}`:"my-xbind-app";i=await prompt("Project name",e)}o||(o=await select("\nSelect runtime:",Object.entries(TEMPLATES).map(([e,t])=>({value:e,label:t.name,description:t.description})),0))}if(!isValidProjectName(i))return console.error("❌ Invalid project name. Use only letters, numbers, hyphens, and underscores."),void(process.exitCode=1);const s=path.resolve(process.cwd(),i);if(fs.existsSync(s))return console.error(`❌ Directory "${i}" already exists.`),void(process.exitCode=1);if(!o||!TEMPLATES[o])return console.error("❌ Invalid runtime selection."),void(process.exitCode=1);const a=TEMPLATES[o];console.log(`\n📦 Creating ${a.name} project: ${i}`);const c=new Spinner("Creating project structure...");c.start();try{await fs.promises.mkdir(s,{recursive:!0}),await copyTemplate(o,s,n),c.succeed("Project structure created")}catch(e){return c.fail("Failed to create project structure"),console.error(e instanceof Error?e.message:String(e)),void(process.exitCode=1)}if("none"!==a.packageManager&&"test"!==process.env.NODE_ENV){const e=new Spinner("Installing dependencies...");e.start();try{await installDependencies(s,a.packageManager),e.succeed("Dependencies installed")}catch(t){e.fail("Failed to install dependencies"),console.error("You can install them manually later.")}}if(n||r){const e=n?.url||r||"";process.env.DEBUG_CLI&&console.log("[DEBUG] Writing .env file:",{invite:!!n,inviteUrl:r,finalInviteUrl:e,projectPath:s}),e&&await fs.promises.writeFile(path.join(s,".env"),`XBIND_INVITE_CODE=${e}\n`,"utf-8")}else process.env.DEBUG_CLI&&console.log("[DEBUG] Not writing .env file:",{invite:!!n,inviteUrl:r});console.log("\n✅ Ready!\n"),console.log("Next steps:"),console.log(` cd ${i}`),console.log(` ${a.startCommand}`),n?(console.log(`\n🔗 Connected to: ${n.from.name}`),console.log(` DID: ${n.from.did}`)):console.log("\n💡 To connect to a service, get an invite code and update .env file.")}async function main(e=process.argv.slice(2)){const{values:t}=(0,node_util_1.parseArgs)({args:e,options:{invite:{type:"string",short:"i"},name:{type:"string",short:"n"},runtime:{type:"string",short:"r"},yes:{type:"boolean",short:"y"},"registry-url":{type:"string"},help:{type:"boolean",short:"h"}}});t.help?console.log("\nXBind CLI - One-Line M2M Setup\n\nUsage:\n npx xbind-init [options]\n\nOptions:\n -i, --invite <url> Invite URL or code\n -n, --name <name> Project name\n -r, --runtime <runtime> Runtime template (node-typescript, node-javascript, deno, cloudflare-worker, vercel-function)\n -y, --yes Skip interactive prompts (use defaults)\n --registry-url <url> Custom registry URL (default: https://xbind.to)\n -h, --help Show this help message\n\nExamples:\n npx xbind-init --invite https://xbind.to/invite/XBD-abc123\n npx xbind-init --invite XBD-abc123 --name my-app --runtime node-typescript\n npx xbind-init --yes\n ".trim()):await initCommand({invite:t.invite,name:t.name,runtime:t.runtime,yes:t.yes,"registry-url":t["registry-url"]})}const isDirectRun=process.argv[1]?.endsWith("init.ts")||process.argv[1]?.endsWith("init.js");isDirectRun&&main().catch(e=>{console.error("Fatal:",e instanceof Error?e.message:String(e)),process.exitCode=1});
2
+ "use strict";
3
+ /* eslint-disable no-console */
4
+ /**
5
+ * @module cli/init
6
+ * One-line CLI setup for XBind connections.
7
+ *
8
+ * Enables: npx xbind-init --invite <code>
9
+ *
10
+ * Flow:
11
+ * 1. Parse invite URL or code
12
+ * 2. Fetch invite details from registry server
13
+ * 3. Interactive prompts for: project name, runtime, TypeScript vs JavaScript
14
+ * 4. Generate project directory with template files
15
+ * 5. Install dependencies
16
+ * 6. Write .env file with XBIND_INVITE_CODE
17
+ * 7. Register with XBind registry (auto-accept flow)
18
+ * 8. Print success message with next steps
19
+ *
20
+ * @example
21
+ * ```bash
22
+ * npx xbind-init --invite https://xbind.to/invite/XBD-abc123
23
+ *
24
+ * # Prompts:
25
+ * # → Project name: my-xbind-app
26
+ * # → Runtime: node-typescript
27
+ * # Creating project...
28
+ * # Installing dependencies...
29
+ * # Registering with XBind...
30
+ * # ✅ Ready! Run: cd my-xbind-app && npm start
31
+ * ```
32
+ */
33
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
34
+ if (k2 === undefined) k2 = k;
35
+ var desc = Object.getOwnPropertyDescriptor(m, k);
36
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
37
+ desc = { enumerable: true, get: function() { return m[k]; } };
38
+ }
39
+ Object.defineProperty(o, k2, desc);
40
+ }) : (function(o, m, k, k2) {
41
+ if (k2 === undefined) k2 = k;
42
+ o[k2] = m[k];
43
+ }));
44
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
45
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
46
+ }) : function(o, v) {
47
+ o["default"] = v;
48
+ });
49
+ var __importStar = (this && this.__importStar) || (function () {
50
+ var ownKeys = function(o) {
51
+ ownKeys = Object.getOwnPropertyNames || function (o) {
52
+ var ar = [];
53
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
54
+ return ar;
55
+ };
56
+ return ownKeys(o);
57
+ };
58
+ return function (mod) {
59
+ if (mod && mod.__esModule) return mod;
60
+ var result = {};
61
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
62
+ __setModuleDefault(result, mod);
63
+ return result;
64
+ };
65
+ })();
66
+ Object.defineProperty(exports, "__esModule", { value: true });
67
+ exports.initCommand = initCommand;
68
+ exports.main = main;
69
+ const node_util_1 = require("node:util");
70
+ const fs = __importStar(require("node:fs"));
71
+ const path = __importStar(require("node:path"));
72
+ const node_child_process_1 = require("node:child_process");
73
+ const readline = __importStar(require("node:readline/promises"));
74
+ const node_process_1 = require("node:process");
75
+ const invite_js_1 = require("../invite.js");
76
+ // Get template directory path
77
+ // In production, templates are at ../templates relative to dist/cli/init.js
78
+ // We'll resolve this dynamically based on the package root
79
+ function getTemplateDir() {
80
+ // Find package root by looking for package.json
81
+ let currentDir = __dirname;
82
+ while (currentDir !== '/') {
83
+ if (fs.existsSync(path.join(currentDir, 'package.json'))) {
84
+ return path.join(currentDir, 'templates');
85
+ }
86
+ currentDir = path.dirname(currentDir);
87
+ }
88
+ // Fallback: assume we're in dist/cli and templates are in package root
89
+ return path.join(__dirname, '../../templates');
90
+ }
91
+ const TEMPLATES = {
92
+ 'node-typescript': {
93
+ name: 'Node.js + TypeScript',
94
+ description: 'Node.js with TypeScript, best for backend services',
95
+ packageManager: 'npm',
96
+ entryPoint: 'src/index.ts',
97
+ startCommand: 'npm run dev',
98
+ },
99
+ 'node-javascript': {
100
+ name: 'Node.js + JavaScript',
101
+ description: 'Node.js with JavaScript, minimal setup',
102
+ packageManager: 'npm',
103
+ entryPoint: 'src/index.js',
104
+ startCommand: 'npm start',
105
+ },
106
+ 'deno': {
107
+ name: 'Deno',
108
+ description: 'Modern TypeScript runtime',
109
+ packageManager: 'deno',
110
+ entryPoint: 'mod.ts',
111
+ startCommand: 'deno run --allow-net --allow-env --allow-read mod.ts',
112
+ },
113
+ 'cloudflare-worker': {
114
+ name: 'Cloudflare Worker',
115
+ description: 'Edge runtime on Cloudflare',
116
+ packageManager: 'npm',
117
+ entryPoint: 'src/index.ts',
118
+ startCommand: 'npm run dev',
119
+ },
120
+ 'vercel-function': {
121
+ name: 'Vercel Function',
122
+ description: 'Serverless function on Vercel',
123
+ packageManager: 'npm',
124
+ entryPoint: 'api/xbind.ts',
125
+ startCommand: 'npm run dev',
126
+ },
127
+ };
128
+ /**
129
+ * Spinner for progress indication.
130
+ */
131
+ class Spinner {
132
+ frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
133
+ currentFrame = 0;
134
+ intervalId;
135
+ message;
136
+ constructor(message) {
137
+ this.message = message;
138
+ }
139
+ start() {
140
+ this.intervalId = setInterval(() => {
141
+ const frame = this.frames[this.currentFrame];
142
+ process.stdout.write(`\r${frame} ${this.message}`);
143
+ this.currentFrame = (this.currentFrame + 1) % this.frames.length;
144
+ }, 80);
145
+ }
146
+ succeed(message) {
147
+ this.stop();
148
+ process.stdout.write(`\r✅ ${message ?? this.message}\n`);
149
+ }
150
+ fail(message) {
151
+ this.stop();
152
+ process.stdout.write(`\r❌ ${message ?? this.message}\n`);
153
+ }
154
+ stop() {
155
+ if (this.intervalId) {
156
+ clearInterval(this.intervalId);
157
+ this.intervalId = undefined;
158
+ }
159
+ }
160
+ }
161
+ /**
162
+ * Parse invite code/URL to extract invite ID.
163
+ *
164
+ * @param inviteInput - Invite URL or code
165
+ * @returns Invite URL
166
+ */
167
+ function normalizeInviteUrl(inviteInput, registryUrl) {
168
+ // If it's already a full URL, return as-is
169
+ if (inviteInput.startsWith('http://') || inviteInput.startsWith('https://')) {
170
+ return inviteInput;
171
+ }
172
+ // If it starts with XBD-, treat as code
173
+ if (inviteInput.startsWith('XBD-')) {
174
+ return `${registryUrl}/invite/${inviteInput}`;
175
+ }
176
+ // Otherwise, assume it's an ID
177
+ return `${registryUrl}/invite/${inviteInput}`;
178
+ }
179
+ /**
180
+ * Validate project name.
181
+ *
182
+ * @param name - Project name
183
+ * @returns true if valid
184
+ */
185
+ function isValidProjectName(name) {
186
+ return /^[a-z0-9-_]+$/i.test(name) && name.length > 0 && name.length <= 100;
187
+ }
188
+ /**
189
+ * Prompt user for input.
190
+ *
191
+ * @param question - Question text
192
+ * @param defaultValue - Default value
193
+ * @returns User input
194
+ */
195
+ async function prompt(question, defaultValue) {
196
+ const rl = readline.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
197
+ const answer = await rl.question(defaultValue ? `${question} (${defaultValue}): ` : `${question}: `);
198
+ rl.close();
199
+ return answer.trim() || defaultValue || '';
200
+ }
201
+ /**
202
+ * Prompt user to select from a list.
203
+ *
204
+ * @param question - Question text
205
+ * @param choices - Available choices
206
+ * @param defaultIndex - Default choice index
207
+ * @returns Selected choice
208
+ */
209
+ async function select(question, choices, defaultIndex = 0) {
210
+ console.log(question);
211
+ choices.forEach((choice, i) => {
212
+ const prefix = i === defaultIndex ? '→' : ' ';
213
+ console.log(` ${prefix} ${i + 1}. ${choice.label} - ${choice.description}`);
214
+ });
215
+ const rl = readline.createInterface({ input: node_process_1.stdin, output: node_process_1.stdout });
216
+ const answer = await rl.question(`Select (1-${choices.length}): `);
217
+ rl.close();
218
+ const selectedIndex = parseInt(answer.trim(), 10) - 1;
219
+ if (selectedIndex >= 0 && selectedIndex < choices.length) {
220
+ return choices[selectedIndex]?.value ?? choices[defaultIndex]?.value ?? '';
221
+ }
222
+ return choices[defaultIndex]?.value ?? '';
223
+ }
224
+ /**
225
+ * Run shell command.
226
+ *
227
+ * @param command - Command to run
228
+ * @param args - Command arguments
229
+ * @param cwd - Working directory
230
+ * @returns Promise that resolves when command completes
231
+ */
232
+ function runCommand(command, args, cwd) {
233
+ return new Promise((resolve, reject) => {
234
+ const proc = (0, node_child_process_1.spawn)(command, args, {
235
+ cwd,
236
+ stdio: 'ignore',
237
+ shell: true,
238
+ });
239
+ proc.on('close', (code) => {
240
+ if (code === 0) {
241
+ resolve();
242
+ }
243
+ else {
244
+ reject(new Error(`Command failed with code ${code ?? 'unknown'}`));
245
+ }
246
+ });
247
+ proc.on('error', reject);
248
+ });
249
+ }
250
+ /**
251
+ * Copy template files to project directory.
252
+ *
253
+ * @param templateName - Template name
254
+ * @param projectPath - Project directory path
255
+ * @param invite - Invite details
256
+ */
257
+ async function copyTemplate(templateName, projectPath, invite) {
258
+ const templateDir = path.join(getTemplateDir(), templateName);
259
+ // Read all files in template directory
260
+ const files = await fs.promises.readdir(templateDir, { recursive: true, withFileTypes: true });
261
+ for (const file of files) {
262
+ if (file.isFile()) {
263
+ // Get the parent path from the file dirent
264
+ // Note: file.parentPath was added in Node.js 20.1.0, file.path is deprecated
265
+ const parentPath = file.parentPath || file.path || templateDir;
266
+ const relativePath = path.relative(templateDir, path.join(parentPath, file.name));
267
+ const sourcePath = path.join(templateDir, relativePath);
268
+ const destPath = path.join(projectPath, relativePath);
269
+ // Create directory if it doesn't exist
270
+ await fs.promises.mkdir(path.dirname(destPath), { recursive: true });
271
+ // Read template file
272
+ let content = await fs.promises.readFile(sourcePath, 'utf-8');
273
+ // Replace placeholders
274
+ if (invite) {
275
+ content = content.replace(/{{INVITE_URL}}/g, invite.url);
276
+ content = content.replace(/{{INVITE_ID}}/g, invite.id);
277
+ content = content.replace(/{{SERVICE_NAME}}/g, invite.from.name);
278
+ content = content.replace(/{{SERVICE_DID}}/g, invite.from.did);
279
+ content = content.replace(/{{SERVICE_ENDPOINT}}/g, invite.from.endpoint);
280
+ }
281
+ // Write to destination
282
+ await fs.promises.writeFile(destPath, content, 'utf-8');
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * Install dependencies.
288
+ *
289
+ * @param projectPath - Project directory
290
+ * @param packageManager - Package manager to use
291
+ */
292
+ async function installDependencies(projectPath, packageManager) {
293
+ if (packageManager === 'npm') {
294
+ await runCommand('npm', ['install'], projectPath);
295
+ }
296
+ else if (packageManager === 'deno') {
297
+ // Deno doesn't need install, it auto-downloads
298
+ }
299
+ // 'none' for templates that don't need dependencies
300
+ }
301
+ /**
302
+ * Main init command.
303
+ *
304
+ * @param options - Init options
305
+ */
306
+ async function initCommand(options = {}) {
307
+ const registryUrl = options.registryUrl || 'https://xbind.to';
308
+ // Step 1: Get invite details
309
+ let invite;
310
+ let inviteUrl;
311
+ if (options.invite) {
312
+ inviteUrl = normalizeInviteUrl(options.invite, registryUrl);
313
+ const spinner = new Spinner('Fetching invite details...');
314
+ spinner.start();
315
+ try {
316
+ const inviteService = new invite_js_1.InviteService({ inviteApiUrl: registryUrl });
317
+ const inviteResult = await inviteService.get(inviteUrl);
318
+ if (!inviteResult.ok) {
319
+ spinner.fail(`Failed to fetch invite: ${inviteResult.error.message}`);
320
+ if (inviteResult.error.hint) {
321
+ console.error(`Hint: ${inviteResult.error.hint}`);
322
+ }
323
+ process.exitCode = 1;
324
+ return;
325
+ }
326
+ invite = inviteResult.value;
327
+ // TypeScript narrowing: invite is guaranteed to be defined here
328
+ if (!invite) {
329
+ spinner.fail('Invalid invite data received');
330
+ process.exitCode = 1;
331
+ return;
332
+ }
333
+ spinner.succeed(`Connected to ${invite.from.name}`);
334
+ }
335
+ catch (error) {
336
+ spinner.fail('Failed to fetch invite details');
337
+ console.error(error instanceof Error ? error.message : String(error));
338
+ process.exitCode = 1;
339
+ return;
340
+ }
341
+ }
342
+ // Step 2: Prompt for project details (if not in --yes mode)
343
+ let projectName = options.name;
344
+ let runtime = options.runtime;
345
+ if (!options.yes) {
346
+ // Prompt for project name
347
+ if (!projectName) {
348
+ const suggestedName = invite ? `connect-${invite.from.name}` : 'my-xbind-app';
349
+ projectName = await prompt('Project name', suggestedName);
350
+ }
351
+ // Prompt for runtime
352
+ if (!runtime) {
353
+ runtime = (await select('\nSelect runtime:', Object.entries(TEMPLATES).map(([value, meta]) => ({
354
+ value,
355
+ label: meta.name,
356
+ description: meta.description,
357
+ })), 0));
358
+ }
359
+ }
360
+ else {
361
+ // In --yes mode, use defaults
362
+ projectName = projectName || 'my-xbind-app';
363
+ runtime = runtime || 'node-typescript';
364
+ }
365
+ // Validate project name (applies to both modes)
366
+ if (!isValidProjectName(projectName)) {
367
+ console.error('❌ Invalid project name. Use only letters, numbers, hyphens, and underscores.');
368
+ process.exitCode = 1;
369
+ return;
370
+ }
371
+ // Check if directory exists (applies to both modes)
372
+ const projectPath = path.resolve(process.cwd(), projectName);
373
+ if (fs.existsSync(projectPath)) {
374
+ console.error(`❌ Directory "${projectName}" already exists.`);
375
+ process.exitCode = 1;
376
+ return;
377
+ }
378
+ if (!runtime || !TEMPLATES[runtime]) {
379
+ console.error('❌ Invalid runtime selection.');
380
+ process.exitCode = 1;
381
+ return;
382
+ }
383
+ const template = TEMPLATES[runtime];
384
+ console.log(`\n📦 Creating ${template.name} project: ${projectName}`);
385
+ // Step 3: Create project directory
386
+ const createSpinner = new Spinner('Creating project structure...');
387
+ createSpinner.start();
388
+ try {
389
+ await fs.promises.mkdir(projectPath, { recursive: true });
390
+ await copyTemplate(runtime, projectPath, invite);
391
+ createSpinner.succeed('Project structure created');
392
+ }
393
+ catch (error) {
394
+ createSpinner.fail('Failed to create project structure');
395
+ console.error(error instanceof Error ? error.message : String(error));
396
+ process.exitCode = 1;
397
+ return;
398
+ }
399
+ // Step 4: Install dependencies
400
+ if (template.packageManager !== 'none' && process.env.NODE_ENV !== 'test') {
401
+ const installSpinner = new Spinner('Installing dependencies...');
402
+ installSpinner.start();
403
+ try {
404
+ await installDependencies(projectPath, template.packageManager);
405
+ installSpinner.succeed('Dependencies installed');
406
+ }
407
+ catch (error) {
408
+ installSpinner.fail('Failed to install dependencies');
409
+ console.error('You can install them manually later.');
410
+ // Don't exit, continue
411
+ }
412
+ }
413
+ // Step 5: Write .env file with invite code (if provided)
414
+ if (invite || inviteUrl) {
415
+ const finalInviteUrl = invite?.url || inviteUrl || '';
416
+ if (process.env.DEBUG_CLI) {
417
+ console.log('[DEBUG] Writing .env file:', { invite: !!invite, inviteUrl, finalInviteUrl, projectPath });
418
+ }
419
+ if (finalInviteUrl) {
420
+ await fs.promises.writeFile(path.join(projectPath, '.env'), `XBIND_INVITE_CODE=${finalInviteUrl}\n`, 'utf-8');
421
+ }
422
+ }
423
+ else if (process.env.DEBUG_CLI) {
424
+ console.log('[DEBUG] Not writing .env file:', { invite: !!invite, inviteUrl });
425
+ }
426
+ // Step 6: Print success message
427
+ console.log('\n✅ Ready!\n');
428
+ console.log('Next steps:');
429
+ console.log(` cd ${projectName}`);
430
+ console.log(` ${template.startCommand}`);
431
+ if (invite) {
432
+ console.log(`\n🔗 Connected to: ${invite.from.name}`);
433
+ console.log(` DID: ${invite.from.did}`);
434
+ }
435
+ else {
436
+ console.log('\n💡 To connect to a service, get an invite code and update .env file.');
437
+ }
438
+ }
439
+ /**
440
+ * CLI entry point.
441
+ *
442
+ * @param argv - Command-line arguments
443
+ */
444
+ async function main(argv = process.argv.slice(2)) {
445
+ const { values } = (0, node_util_1.parseArgs)({
446
+ args: argv,
447
+ options: {
448
+ invite: { type: 'string', short: 'i' },
449
+ name: { type: 'string', short: 'n' },
450
+ runtime: { type: 'string', short: 'r' },
451
+ yes: { type: 'boolean', short: 'y' },
452
+ 'registry-url': { type: 'string' },
453
+ help: { type: 'boolean', short: 'h' },
454
+ },
455
+ });
456
+ if (values.help) {
457
+ console.log(`
458
+ XBind CLI - One-Line M2M Setup
459
+
460
+ Usage:
461
+ npx xbind-init [options]
462
+
463
+ Options:
464
+ -i, --invite <url> Invite URL or code
465
+ -n, --name <name> Project name
466
+ -r, --runtime <runtime> Runtime template (node-typescript, node-javascript, deno, cloudflare-worker, vercel-function)
467
+ -y, --yes Skip interactive prompts (use defaults)
468
+ --registry-url <url> Custom registry URL (default: https://xbind.to)
469
+ -h, --help Show this help message
470
+
471
+ Examples:
472
+ npx xbind-init --invite https://xbind.to/invite/XBD-abc123
473
+ npx xbind-init --invite XBD-abc123 --name my-app --runtime node-typescript
474
+ npx xbind-init --yes
475
+ `.trim());
476
+ return;
477
+ }
478
+ await initCommand({
479
+ invite: values.invite,
480
+ name: values.name,
481
+ runtime: values.runtime,
482
+ yes: values.yes,
483
+ 'registry-url': values['registry-url'],
484
+ });
485
+ }
486
+ // Auto-run if executed directly
487
+ const isDirectRun = process.argv[1]?.endsWith('init.ts') || process.argv[1]?.endsWith('init.js');
488
+ if (isDirectRun) {
489
+ main().catch((error) => {
490
+ console.error('Fatal:', error instanceof Error ? error.message : String(error));
491
+ process.exitCode = 1;
492
+ });
493
+ }