{"id":13695834,"url":"https://github.com/Microsoft/BotFramework-DirectLineJS","last_synced_at":"2025-05-03T13:33:30.911Z","repository":{"id":16444866,"uuid":"79851706","full_name":"microsoft/BotFramework-DirectLineJS","owner":"microsoft","description":"JavaScript client library for Microsoft Bot Framework's Direct Line protocol","archived":false,"fork":false,"pushed_at":"2025-04-18T17:01:10.000Z","size":1404,"stargazers_count":197,"open_issues_count":83,"forks_count":129,"subscribers_count":42,"default_branch":"master","last_synced_at":"2025-04-30T06:34:54.452Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microsoft.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"Contributing.md","funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-01-23T21:47:55.000Z","updated_at":"2025-04-18T17:01:13.000Z","dependencies_parsed_at":"2024-06-18T12:32:22.278Z","dependency_job_id":"9949f22f-924b-4ddb-a5da-6f3deeb9e4bd","html_url":"https://github.com/microsoft/BotFramework-DirectLineJS","commit_stats":{"total_commits":187,"total_committers":36,"mean_commits":5.194444444444445,"dds":0.7967914438502673,"last_synced_commit":"31ba05bb007fa08e5bb132beccfcf987f83e0f19"},"previous_names":[],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FBotFramework-DirectLineJS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FBotFramework-DirectLineJS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FBotFramework-DirectLineJS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FBotFramework-DirectLineJS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microsoft","download_url":"https://codeload.github.com/microsoft/BotFramework-DirectLineJS/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252195940,"owners_count":21709740,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T18:00:33.952Z","updated_at":"2025-05-03T13:33:30.875Z","avatar_url":"https://github.com/microsoft.png","language":"TypeScript","funding_links":[],"categories":["First Party"],"sub_categories":[],"readme":"![Bot Framework DirectLineJS](./docs/media/FrameWorkDirectLineJS@1x.png)\n\n# Microsoft Bot Framework Direct Line JS Client\n\n[![Build Status](https://travis-ci.org/Microsoft/BotFramework-DirectLineJS.svg?branch=master)](https://travis-ci.org/Microsoft/BotFramework-DirectLineJS)\n\nClient library for the [Microsoft Bot Framework](http://www.botframework.com) _[Direct Line](https://docs.botframework.com/en-us/restapi/directline3/)_ protocol.\n\nUsed by [WebChat](https://github.com/Microsoft/BotFramework-WebChat) and thus (by extension) [Emulator](https://github.com/Microsoft/BotFramework-Emulator), WebChat channel, and [Azure Bot Service](https://azure.microsoft.com/en-us/services/bot-service/).\n\n## FAQ\n\n### _Who is this for?_\n\nAnyone who is building a Bot Framework JavaScript client who does not want to use [WebChat](https://github.com/Microsoft/BotFramework-WebChat).\n\nIf you're currently using WebChat, you don't need to make any changes as it includes this package.\n\n### _What is that funny `subscribe()` method in the samples below?_\n\nInstead of callbacks or Promises, this library handles async operations using Observables. Try it, you'll like it! For more information, check out [RxJS](https://github.com/reactivex/rxjs/).\n\n### _Can I use [TypeScript](http://www.typescriptlang.com)?_\n\nYou bet.\n\n### How ready for prime time is this library?\n\nThis is an official Microsoft-supported library, and is considered largely complete. Future changes (aside from supporting future updates to the Direct Line protocol) will likely be limited to bug fixes, performance improvements, tutorials, and samples. The big missing piece here is unit tests.\n\nThat said, the public API is still subject to change.\n\n### Why the library did not detect Web Socket disconnections?\n\nOn iOS/iPadOS, when network change from Wi-Fi to cellular, the `WebSocket` object will be stalled without any errors. This is not detectable nor workaroundable without any additional assistance. The issue is related to an experimental feature named \"NSURLSession WebSocket\". The feature is enabled by default on iOS/iPadOS 15 and up.\n\nAn option named `networkInformation` can be used to assist the library to detect any connection issues. The option is based on [W3C Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) and it should implement at least 2 members:\n\n- [A `type` property](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type) to indicate the current network type\n  - When the `type` is `\"offline\"`, network is not available and no connection will be made\n- [A `change` event](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/change_event) should dispatch when the `type` property change\n\nHowever, Safari on iOS/iPadOS [does not support W3C Network Information API](https://bugs.webkit.org/show_bug.cgi?id=185697). It is up to web developers to implement the `NetworkInformation` polyfill.\n\nOne effective way to detect network type change is to subscribe to a [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) source. The service would send a message every 30 seconds. If network type changed and current network type is no longer available, the connection will be closed prematurely and an `error` event will be dispatched to the [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) instance. Upon receiving the `error` event, the `NetworkInformation.type` should then change to `\"offline\"`. The browser would automatically retry the Server-Sent Events connection. Upon receiving an `open` event, the polyfill should change the `type` back to `\"unknown\"`.\n\nIf the library is being used in a native iOS/iPadOS app, a less resource-intensive solution would be partially implementing the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) using [`NWPathMonitor`](https://developer.apple.com/documentation/network/nwpathmonitor). When network change happens, the `NetworkInformation` instance should update the [`type` property](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type) based on network type and dispatch a [`change` event](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/change_event).\n\n## How to build from source\n\n0. Clone this repo\n1. `npm install`\n2. `npm run build` (or `npm run watch` to rebuild on every change, or `npm run prepublishOnly` to build production)\n\n## How to include in your app\n\nThere are several ways:\n\n1. Build from scratch and include either `/directLine.js` (webpacked with rxjs) or `lib/directline.js` in your app\n2. `npm install botframework-directlinejs`\n\n## Using from within a Node environment\n\nThis library uses RxJs/AjaxObserverable which is meant for use in a DOM environment. That doesn't mean you can't also use it from Node though, you just need to do a couple of extra things:\n\n1. `npm install --save ws xhr2`\n2. Add the following towards the top of your main application file:\n\n```typescript\nglobal.XMLHttpRequest = require('xhr2');\nglobal.WebSocket = require('ws');\n```\n\n## How to create and use a directLine object\n\n### Obtain security credentials for your bot:\n\n1. If you haven't already, [register your bot](https://azure.microsoft.com/en-us/services/bot-service/).\n2. Add a DirectLine (**not WebChat**) channel, and generate a Direct Line Secret. Make sure Direct Line 3.0 is enabled.\n3. For testing you can use your Direct Line Secret as a security token, but for production you will likely want to exchange that Secret for a Token as detailed in the Direct Line [documentation](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-channel-directline?view=azure-bot-service-4.0).\n\n### Create a DirectLine object:\n\n```typescript\nimport { DirectLine } from 'botframework-directlinejs';\n// For Node.js:\n// const { DirectLine } = require('botframework-directlinejs');\n\nvar directLine = new DirectLine({\n    secret: /* put your Direct Line secret here */,\n    token: /* or put your Direct Line token here (supply secret OR token, not both) */,\n    domain: /* optional: if you are not using the default Direct Line endpoint, e.g. if you are using a region-specific endpoint, put its full URL here */\n    webSocket: /* optional: false if you want to use polling GET to receive messages. Defaults to true (use WebSocket). */,\n    pollingInterval: /* optional: set polling interval in milliseconds. Defaults to 1000 */,\n    timeout: /* optional: a timeout in milliseconds for requests to the bot. Defaults to 20000 */,\n    conversationStartProperties: { /* optional: properties to send to the bot on conversation start */\n        locale: 'en-US'\n    }\n});\n```\n\n### Post activities to the bot:\n\n```typescript\ndirectLine\n  .postActivity({\n    from: { id: 'myUserId', name: 'myUserName' }, // required (from.name is optional)\n    type: 'message',\n    text: 'a message for you, Rudy'\n  })\n  .subscribe(\n    id =\u003e console.log('Posted activity, assigned ID ', id),\n    error =\u003e console.log('Error posting activity', error)\n  );\n```\n\nYou can also post messages with attachments, and non-message activities such as events, by supplying the appropriate fields in the activity.\n\n### Listen to activities sent from the bot:\n\n```typescript\ndirectLine.activity$.subscribe(activity =\u003e console.log('received activity ', activity));\n```\n\nYou can use RxJS operators on incoming activities. To see only message activities:\n\n```typescript\ndirectLine.activity$\n  .filter(activity =\u003e activity.type === 'message')\n  .subscribe(message =\u003e console.log('received message ', message));\n```\n\nDirect Line will helpfully send your client a copy of every sent activity, so a common pattern is to filter incoming messages on `from`:\n\n```typescript\ndirectLine.activity$\n  .filter(activity =\u003e activity.type === 'message' \u0026\u0026 activity.from.id === 'yourBotHandle')\n  .subscribe(message =\u003e console.log('received message ', message));\n```\n\n### Monitor connection status\n\nSubscribing to either `postActivity` or `activity$` will start the process of connecting to the bot. Your app can listen to the connection status and react appropriately :\n\n```typescript\nimport { ConnectionStatus } from 'botframework-directlinejs';\n\ndirectLine.connectionStatus$.subscribe(connectionStatus =\u003e {\n  switch (connectionStatus) {\n    case ConnectionStatus.Uninitialized: // the status when the DirectLine object is first created/constructed\n    case ConnectionStatus.Connecting: // currently trying to connect to the conversation\n    case ConnectionStatus.Online: // successfully connected to the converstaion. Connection is healthy so far as we know.\n    case ConnectionStatus.ExpiredToken: // last operation errored out with an expired token. Your app should supply a new one.\n    case ConnectionStatus.FailedToConnect: // the initial attempt to connect to the conversation failed. No recovery possible.\n    case ConnectionStatus.Ended: // the bot ended the conversation\n  }\n});\n```\n\n### Reconnect to a conversation\n\nIf your app created your DirectLine object by passing a token, DirectLine will refresh that token every 15 minutes.\nShould your client lose connectivity (e.g. close laptop, fail to pay Internet access bill, go under a tunnel), `connectionStatus$`\nwill change to `ConnectionStatus.ExpiredToken`. Your app can request a new token from its server, which should call\nthe [Reconnect](https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-reconnect-to-conversation?view=azure-bot-service-4.0) API.\nThe resultant Conversation object can then be passed by the app to DirectLine.\n\n```typescript\nvar conversation = /* a Conversation object obtained from your app's server */;\ndirectLine.reconnect(conversation);\n```\n\n### Resume an existing conversation\n\nWhen using DirectLine with WebChat, closing the current tab or refreshing the page will create a new conversation in most cases. You can resume an existing conversation to keep the user in the same context.\n\n**When using a secret** you can resume a conversation by:\n\n- Storing the conversationid (in a _permanent_ place, like local storage)\n- Giving this value back while creating the DirectLine object along with the secret\n\n```typescript\nimport { DirectLine } from 'botframework-directlinejs';\n\nconst dl = new DirectLine({\n    secret: /* SECRET */,\n    conversationId: /* the conversationid you stored from previous conversation */\n});\n```\n\n**When using a token** you can resume a conversation by:\n\n- Storing the conversationid and your token (in a _permanent_ place, like local storage)\n- Calling the DirectLine reconnect API yourself to get a refreshed token and a streamurl\n- Creating the DirectLine object using the ConversationId, Token, and StreamUrl\n\n```typescript\nimport { DirectLine } from 'botframework-directlinejs';\n\nconst dl = new DirectLine({\n    token: /* the token you retrieved while reconnecting */,\n    streamUrl: /* the streamUrl you retrieved while reconnecting */,\n    conversationId: /* the conversationid you stored from previous conversation */\n});\n```\n\n**Getting any history that Direct Line has cached** : you can retrieve history using watermarks:\nYou can see the watermark as an _activity 'bookmark'_. The resuming scenario will replay all the conversation activities from the watermark you specify.\n\n```typescript\nimport { DirectLine } from 'botframework-directlinejs';\n\nconst dl = new DirectLine({\n    token: /* the token you retrieved while reconnecting */,\n    streamUrl: /* the streamUrl you retrieved while reconnecting */,\n    conversationId: /* the conversationid you stored from previous conversation */,\n    watermark: /* a watermark you saved from a previous conversation */,\n    webSocket: false\n});\n```\n\n## Contributing\n\nThis project welcomes contributions and suggestions. Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit https://cla.microsoft.com.\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n\n## Reporting Security Issues\n\nSecurity issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) at [secure@microsoft.com](mailto:secure@microsoft.com). You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the [MSRC PGP](https://technet.microsoft.com/en-us/security/dn606155) key, can be found in the [Security TechCenter](https://technet.microsoft.com/en-us/security/default).\n\nCopyright (c) Microsoft Corporation. All rights reserved.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMicrosoft%2FBotFramework-DirectLineJS","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FMicrosoft%2FBotFramework-DirectLineJS","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMicrosoft%2FBotFramework-DirectLineJS/lists"}